3 * Implements the User class for the %MediaWiki software.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
23 use MediaWiki\MediaWikiServices
;
24 use MediaWiki\Session\SessionManager
;
25 use MediaWiki\Session\Token
;
26 use MediaWiki\Auth\AuthManager
;
27 use MediaWiki\Auth\AuthenticationResponse
;
28 use MediaWiki\Auth\AuthenticationRequest
;
31 * String Some punctuation to prevent editing from broken text-mangling proxies.
32 * @deprecated since 1.27, use \MediaWiki\Session\Token::SUFFIX
35 define( 'EDIT_TOKEN_SUFFIX', Token
::SUFFIX
);
38 * The User object encapsulates all of the user-specific settings (user_id,
39 * name, rights, email address, options, last login time). Client
40 * classes use the getXXX() functions to access these fields. These functions
41 * do all the work of determining whether the user is logged in,
42 * whether the requested option can be satisfied from cookies or
43 * whether a database query is needed. Most of the settings needed
44 * for rendering normal pages are set in the cookie to minimize use
47 class User
implements IDBAccessObject
{
49 * @const int Number of characters in user_token field.
51 const TOKEN_LENGTH
= 32;
54 * @const string An invalid value for user_token
56 const INVALID_TOKEN
= '*** INVALID ***';
59 * Global constant made accessible as class constants so that autoloader
61 * @deprecated since 1.27, use \MediaWiki\Session\Token::SUFFIX
63 const EDIT_TOKEN_SUFFIX
= EDIT_TOKEN_SUFFIX
;
66 * @const int Serialized record version.
71 * Exclude user options that are set to their default value.
74 const GETOPTIONS_EXCLUDE_DEFAULTS
= 1;
79 const CHECK_USER_RIGHTS
= true;
84 const IGNORE_USER_RIGHTS
= false;
87 * Array of Strings List of member variables which are saved to the
88 * shared cache (memcached). Any operation which changes the
89 * corresponding database fields must call a cache-clearing function.
92 protected static $mCacheVars = [
100 'mEmailAuthenticated',
102 'mEmailTokenExpires',
107 // user_properties table
112 * Array of Strings Core rights.
113 * Each of these should have a corresponding message of the form
117 protected static $mCoreRights = [
148 'editusercssjs', # deprecated
161 'move-categorypages',
162 'move-rootuserpages',
166 'override-export-depth',
189 'userrights-interwiki',
197 * String Cached results of getAllRights()
199 protected static $mAllRights = false;
201 /** Cache variables */
212 /** @var string TS_MW timestamp from the DB */
214 /** @var string TS_MW timestamp from cache */
215 protected $mQuickTouched;
219 public $mEmailAuthenticated;
221 protected $mEmailToken;
223 protected $mEmailTokenExpires;
225 protected $mRegistration;
227 protected $mEditCount;
231 protected $mOptionOverrides;
235 * Bool Whether the cache variables have been loaded.
238 public $mOptionsLoaded;
241 * Array with already loaded items or true if all items have been loaded.
243 protected $mLoadedItems = [];
247 * String Initialization data source if mLoadedItems!==true. May be one of:
248 * - 'defaults' anonymous user initialised from class defaults
249 * - 'name' initialise from mName
250 * - 'id' initialise from mId
251 * - 'session' log in from session if possible
253 * Use the User::newFrom*() family of functions to set this.
258 * Lazy-initialized variables, invalidated with clearInstanceCache
262 protected $mDatePreference;
270 protected $mBlockreason;
272 protected $mEffectiveGroups;
274 protected $mImplicitGroups;
276 protected $mFormerGroups;
278 protected $mGlobalBlock;
295 protected $mAllowUsertalk;
298 private $mBlockedFromCreateAccount = false;
300 /** @var integer User::READ_* constant bitfield used to load data */
301 protected $queryFlagsUsed = self
::READ_NORMAL
;
303 public static $idCacheByName = [];
306 * Lightweight constructor for an anonymous user.
307 * Use the User::newFrom* factory functions for other kinds of users.
311 * @see newFromConfirmationCode()
312 * @see newFromSession()
315 public function __construct() {
316 $this->clearInstanceCache( 'defaults' );
322 public function __toString() {
323 return $this->getName();
327 * Test if it's safe to load this User object.
329 * You should typically check this before using $wgUser or
330 * RequestContext::getUser in a method that might be called before the
331 * system has been fully initialized. If the object is unsafe, you should
332 * use an anonymous user:
334 * $user = $wgUser->isSafeToLoad() ? $wgUser : new User;
340 public function isSafeToLoad() {
341 global $wgFullyInitialised;
343 // The user is safe to load if:
344 // * MW_NO_SESSION is undefined AND $wgFullyInitialised is true (safe to use session data)
345 // * mLoadedItems === true (already loaded)
346 // * mFrom !== 'session' (sessions not involved at all)
348 return ( !defined( 'MW_NO_SESSION' ) && $wgFullyInitialised ) ||
349 $this->mLoadedItems
=== true ||
$this->mFrom
!== 'session';
353 * Load the user table data for this object from the source given by mFrom.
355 * @param integer $flags User::READ_* constant bitfield
357 public function load( $flags = self
::READ_NORMAL
) {
358 global $wgFullyInitialised;
360 if ( $this->mLoadedItems
=== true ) {
364 // Set it now to avoid infinite recursion in accessors
365 $oldLoadedItems = $this->mLoadedItems
;
366 $this->mLoadedItems
= true;
367 $this->queryFlagsUsed
= $flags;
369 // If this is called too early, things are likely to break.
370 if ( !$wgFullyInitialised && $this->mFrom
=== 'session' ) {
371 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
372 ->warning( 'User::loadFromSession called before the end of Setup.php', [
373 'exception' => new Exception( 'User::loadFromSession called before the end of Setup.php' ),
375 $this->loadDefaults();
376 $this->mLoadedItems
= $oldLoadedItems;
380 switch ( $this->mFrom
) {
382 $this->loadDefaults();
385 // Make sure this thread sees its own changes
386 if ( wfGetLB()->hasOrMadeRecentMasterChanges() ) {
387 $flags |
= self
::READ_LATEST
;
388 $this->queryFlagsUsed
= $flags;
391 $this->mId
= self
::idFromName( $this->mName
, $flags );
393 // Nonexistent user placeholder object
394 $this->loadDefaults( $this->mName
);
396 $this->loadFromId( $flags );
400 $this->loadFromId( $flags );
403 if ( !$this->loadFromSession() ) {
404 // Loading from session failed. Load defaults.
405 $this->loadDefaults();
407 Hooks
::run( 'UserLoadAfterLoadFromSession', [ $this ] );
410 throw new UnexpectedValueException(
411 "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
416 * Load user table data, given mId has already been set.
417 * @param integer $flags User::READ_* constant bitfield
418 * @return bool False if the ID does not exist, true otherwise
420 public function loadFromId( $flags = self
::READ_NORMAL
) {
421 if ( $this->mId
== 0 ) {
422 // Anonymous users are not in the database (don't need cache)
423 $this->loadDefaults();
427 // Try cache (unless this needs data from the master DB).
428 // NOTE: if this thread called saveSettings(), the cache was cleared.
429 $latest = DBAccessObjectUtils
::hasFlags( $flags, self
::READ_LATEST
);
431 if ( !$this->loadFromDatabase( $flags ) ) {
432 // Can't load from ID
436 $this->loadFromCache();
439 $this->mLoadedItems
= true;
440 $this->queryFlagsUsed
= $flags;
447 * @param string $wikiId
448 * @param integer $userId
450 public static function purge( $wikiId, $userId ) {
451 $cache = ObjectCache
::getMainWANInstance();
452 $key = $cache->makeGlobalKey( 'user', 'id', $wikiId, $userId );
453 $cache->delete( $key );
458 * @param WANObjectCache $cache
461 protected function getCacheKey( WANObjectCache
$cache ) {
462 return $cache->makeGlobalKey( 'user', 'id', wfWikiID(), $this->mId
);
466 * Load user data from shared cache, given mId has already been set.
471 protected function loadFromCache() {
472 $cache = ObjectCache
::getMainWANInstance();
473 $data = $cache->getWithSetCallback(
474 $this->getCacheKey( $cache ),
476 function ( $oldValue, &$ttl, array &$setOpts ) use ( $cache ) {
477 $setOpts +
= Database
::getCacheSetOptions( wfGetDB( DB_REPLICA
) );
478 wfDebug( "User: cache miss for user {$this->mId}\n" );
480 $this->loadFromDatabase( self
::READ_NORMAL
);
482 $this->loadOptions();
485 foreach ( self
::$mCacheVars as $name ) {
486 $data[$name] = $this->$name;
489 $ttl = $cache->adaptiveTTL( wfTimestamp( TS_UNIX
, $this->mTouched
), $ttl );
494 [ 'pcTTL' => $cache::TTL_PROC_LONG
, 'version' => self
::VERSION
]
497 // Restore from cache
498 foreach ( self
::$mCacheVars as $name ) {
499 $this->$name = $data[$name];
505 /** @name newFrom*() static factory methods */
509 * Static factory method for creation from username.
511 * This is slightly less efficient than newFromId(), so use newFromId() if
512 * you have both an ID and a name handy.
514 * @param string $name Username, validated by Title::newFromText()
515 * @param string|bool $validate Validate username. Takes the same parameters as
516 * User::getCanonicalName(), except that true is accepted as an alias
517 * for 'valid', for BC.
519 * @return User|bool User object, or false if the username is invalid
520 * (e.g. if it contains illegal characters or is an IP address). If the
521 * username is not present in the database, the result will be a user object
522 * with a name, zero user ID and default settings.
524 public static function newFromName( $name, $validate = 'valid' ) {
525 if ( $validate === true ) {
528 $name = self
::getCanonicalName( $name, $validate );
529 if ( $name === false ) {
532 // Create unloaded user object
536 $u->setItemLoaded( 'name' );
542 * Static factory method for creation from a given user ID.
544 * @param int $id Valid user ID
545 * @return User The corresponding User object
547 public static function newFromId( $id ) {
551 $u->setItemLoaded( 'id' );
556 * Factory method to fetch whichever user has a given email confirmation code.
557 * This code is generated when an account is created or its e-mail address
560 * If the code is invalid or has expired, returns NULL.
562 * @param string $code Confirmation code
563 * @param int $flags User::READ_* bitfield
566 public static function newFromConfirmationCode( $code, $flags = 0 ) {
567 $db = ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
568 ?
wfGetDB( DB_MASTER
)
569 : wfGetDB( DB_REPLICA
);
571 $id = $db->selectField(
575 'user_email_token' => md5( $code ),
576 'user_email_token_expires > ' . $db->addQuotes( $db->timestamp() ),
580 return $id ? User
::newFromId( $id ) : null;
584 * Create a new user object using data from session. If the login
585 * credentials are invalid, the result is an anonymous user.
587 * @param WebRequest|null $request Object to use; $wgRequest will be used if omitted.
590 public static function newFromSession( WebRequest
$request = null ) {
592 $user->mFrom
= 'session';
593 $user->mRequest
= $request;
598 * Create a new user object from a user row.
599 * The row should have the following fields from the user table in it:
600 * - either user_name or user_id to load further data if needed (or both)
602 * - all other fields (email, etc.)
603 * It is useless to provide the remaining fields if either user_id,
604 * user_name and user_real_name are not provided because the whole row
605 * will be loaded once more from the database when accessing them.
607 * @param stdClass $row A row from the user table
608 * @param array $data Further data to load into the object (see User::loadFromRow for valid keys)
611 public static function newFromRow( $row, $data = null ) {
613 $user->loadFromRow( $row, $data );
618 * Static factory method for creation of a "system" user from username.
620 * A "system" user is an account that's used to attribute logged actions
621 * taken by MediaWiki itself, as opposed to a bot or human user. Examples
622 * might include the 'Maintenance script' or 'Conversion script' accounts
623 * used by various scripts in the maintenance/ directory or accounts such
624 * as 'MediaWiki message delivery' used by the MassMessage extension.
626 * This can optionally create the user if it doesn't exist, and "steal" the
627 * account if it does exist.
629 * "Stealing" an existing user is intended to make it impossible for normal
630 * authentication processes to use the account, effectively disabling the
631 * account for normal use:
632 * - Email is invalidated, to prevent account recovery by emailing a
633 * temporary password and to disassociate the account from the existing
635 * - The token is set to a magic invalid value, to kill existing sessions
636 * and to prevent $this->setToken() calls from resetting the token to a
638 * - SessionManager is instructed to prevent new sessions for the user, to
639 * do things like deauthorizing OAuth consumers.
640 * - AuthManager is instructed to revoke access, to invalidate or remove
641 * passwords and other credentials.
643 * @param string $name Username
644 * @param array $options Options are:
645 * - validate: As for User::getCanonicalName(), default 'valid'
646 * - create: Whether to create the user if it doesn't already exist, default true
647 * - steal: Whether to "disable" the account for normal use if it already
648 * exists, default false
652 public static function newSystemUser( $name, $options = [] ) {
654 'validate' => 'valid',
659 $name = self
::getCanonicalName( $name, $options['validate'] );
660 if ( $name === false ) {
664 $fields = self
::selectFields();
666 $dbw = wfGetDB( DB_MASTER
);
667 $row = $dbw->selectRow(
670 [ 'user_name' => $name ],
674 // No user. Create it?
675 return $options['create'] ? self
::createNew( $name ) : null;
677 $user = self
::newFromRow( $row );
679 // A user is considered to exist as a non-system user if it can
680 // authenticate, or has an email set, or has a non-invalid token.
681 if ( $user->mEmail ||
$user->mToken
!== self
::INVALID_TOKEN ||
682 AuthManager
::singleton()->userCanAuthenticate( $name )
684 // User exists. Steal it?
685 if ( !$options['steal'] ) {
689 AuthManager
::singleton()->revokeAccessForUser( $name );
691 $user->invalidateEmail();
692 $user->mToken
= self
::INVALID_TOKEN
;
693 $user->saveSettings();
694 SessionManager
::singleton()->preventSessionsForUser( $user->getName() );
703 * Get the username corresponding to a given user ID
704 * @param int $id User ID
705 * @return string|bool The corresponding username
707 public static function whoIs( $id ) {
708 return UserCache
::singleton()->getProp( $id, 'name' );
712 * Get the real name of a user given their user ID
714 * @param int $id User ID
715 * @return string|bool The corresponding user's real name
717 public static function whoIsReal( $id ) {
718 return UserCache
::singleton()->getProp( $id, 'real_name' );
722 * Get database id given a user name
723 * @param string $name Username
724 * @param integer $flags User::READ_* constant bitfield
725 * @return int|null The corresponding user's ID, or null if user is nonexistent
727 public static function idFromName( $name, $flags = self
::READ_NORMAL
) {
728 $nt = Title
::makeTitleSafe( NS_USER
, $name );
729 if ( is_null( $nt ) ) {
734 if ( !( $flags & self
::READ_LATEST
) && isset( self
::$idCacheByName[$name] ) ) {
735 return self
::$idCacheByName[$name];
738 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
739 $db = wfGetDB( $index );
744 [ 'user_name' => $nt->getText() ],
749 if ( $s === false ) {
752 $result = $s->user_id
;
755 self
::$idCacheByName[$name] = $result;
757 if ( count( self
::$idCacheByName ) > 1000 ) {
758 self
::$idCacheByName = [];
765 * Reset the cache used in idFromName(). For use in tests.
767 public static function resetIdByNameCache() {
768 self
::$idCacheByName = [];
772 * Does the string match an anonymous IP address?
774 * This function exists for username validation, in order to reject
775 * usernames which are similar in form to IP addresses. Strings such
776 * as 300.300.300.300 will return true because it looks like an IP
777 * address, despite not being strictly valid.
779 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
780 * address because the usemod software would "cloak" anonymous IP
781 * addresses like this, if we allowed accounts like this to be created
782 * new users could get the old edits of these anonymous users.
784 * @param string $name Name to match
787 public static function isIP( $name ) {
788 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name )
789 || IP
::isIPv6( $name );
793 * Is the input a valid username?
795 * Checks if the input is a valid username, we don't want an empty string,
796 * an IP address, anything that contains slashes (would mess up subpages),
797 * is longer than the maximum allowed username size or doesn't begin with
800 * @param string $name Name to match
803 public static function isValidUserName( $name ) {
804 global $wgContLang, $wgMaxNameChars;
807 || User
::isIP( $name )
808 ||
strpos( $name, '/' ) !== false
809 ||
strlen( $name ) > $wgMaxNameChars
810 ||
$name != $wgContLang->ucfirst( $name )
815 // Ensure that the name can't be misresolved as a different title,
816 // such as with extra namespace keys at the start.
817 $parsed = Title
::newFromText( $name );
818 if ( is_null( $parsed )
819 ||
$parsed->getNamespace()
820 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
824 // Check an additional blacklist of troublemaker characters.
825 // Should these be merged into the title char list?
826 $unicodeBlacklist = '/[' .
827 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
828 '\x{00a0}' . # non-breaking space
829 '\x{2000}-\x{200f}' . # various whitespace
830 '\x{2028}-\x{202f}' . # breaks and control chars
831 '\x{3000}' . # ideographic space
832 '\x{e000}-\x{f8ff}' . # private use
834 if ( preg_match( $unicodeBlacklist, $name ) ) {
842 * Usernames which fail to pass this function will be blocked
843 * from user login and new account registrations, but may be used
844 * internally by batch processes.
846 * If an account already exists in this form, login will be blocked
847 * by a failure to pass this function.
849 * @param string $name Name to match
852 public static function isUsableName( $name ) {
853 global $wgReservedUsernames;
854 // Must be a valid username, obviously ;)
855 if ( !self
::isValidUserName( $name ) ) {
859 static $reservedUsernames = false;
860 if ( !$reservedUsernames ) {
861 $reservedUsernames = $wgReservedUsernames;
862 Hooks
::run( 'UserGetReservedNames', [ &$reservedUsernames ] );
865 // Certain names may be reserved for batch processes.
866 foreach ( $reservedUsernames as $reserved ) {
867 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
868 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->text();
870 if ( $reserved == $name ) {
878 * Return the users who are members of the given group(s). In case of multiple groups,
879 * users who are members of at least one of them are returned.
881 * @param string|array $groups A single group name or an array of group names
882 * @param int $limit Max number of users to return. The actual limit will never exceed 5000
883 * records; larger values are ignored.
884 * @param int $after ID the user to start after
885 * @return UserArrayFromResult
887 public static function findUsersByGroup( $groups, $limit = 5000, $after = null ) {
888 if ( $groups === [] ) {
889 return UserArrayFromResult
::newFromIDs( [] );
892 $groups = array_unique( (array)$groups );
893 $limit = min( 5000, $limit );
895 $conds = [ 'ug_group' => $groups ];
896 if ( $after !== null ) {
897 $conds[] = 'ug_user > ' . (int)$after;
900 $dbr = wfGetDB( DB_REPLICA
);
901 $ids = $dbr->selectFieldValues(
908 'ORDER BY' => 'ug_user',
912 return UserArray
::newFromIDs( $ids );
916 * Usernames which fail to pass this function will be blocked
917 * from new account registrations, but may be used internally
918 * either by batch processes or by user accounts which have
919 * already been created.
921 * Additional blacklisting may be added here rather than in
922 * isValidUserName() to avoid disrupting existing accounts.
924 * @param string $name String to match
927 public static function isCreatableName( $name ) {
928 global $wgInvalidUsernameCharacters;
930 // Ensure that the username isn't longer than 235 bytes, so that
931 // (at least for the builtin skins) user javascript and css files
932 // will work. (bug 23080)
933 if ( strlen( $name ) > 235 ) {
934 wfDebugLog( 'username', __METHOD__
.
935 ": '$name' invalid due to length" );
939 // Preg yells if you try to give it an empty string
940 if ( $wgInvalidUsernameCharacters !== '' ) {
941 if ( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
942 wfDebugLog( 'username', __METHOD__
.
943 ": '$name' invalid due to wgInvalidUsernameCharacters" );
948 return self
::isUsableName( $name );
952 * Is the input a valid password for this user?
954 * @param string $password Desired password
957 public function isValidPassword( $password ) {
958 // simple boolean wrapper for getPasswordValidity
959 return $this->getPasswordValidity( $password ) === true;
963 * Given unvalidated password input, return error message on failure.
965 * @param string $password Desired password
966 * @return bool|string|array True on success, string or array of error message on failure
968 public function getPasswordValidity( $password ) {
969 $result = $this->checkPasswordValidity( $password );
970 if ( $result->isGood() ) {
974 foreach ( $result->getErrorsByType( 'error' ) as $error ) {
975 $messages[] = $error['message'];
977 foreach ( $result->getErrorsByType( 'warning' ) as $warning ) {
978 $messages[] = $warning['message'];
980 if ( count( $messages ) === 1 ) {
988 * Check if this is a valid password for this user
990 * Create a Status object based on the password's validity.
991 * The Status should be set to fatal if the user should not
992 * be allowed to log in, and should have any errors that
993 * would block changing the password.
995 * If the return value of this is not OK, the password
996 * should not be checked. If the return value is not Good,
997 * the password can be checked, but the user should not be
998 * able to set their password to this.
1000 * @param string $password Desired password
1001 * @param string $purpose one of 'login', 'create', 'reset'
1005 public function checkPasswordValidity( $password, $purpose = 'login' ) {
1006 global $wgPasswordPolicy;
1008 $upp = new UserPasswordPolicy(
1009 $wgPasswordPolicy['policies'],
1010 $wgPasswordPolicy['checks']
1013 $status = Status
::newGood();
1014 $result = false; // init $result to false for the internal checks
1016 if ( !Hooks
::run( 'isValidPassword', [ $password, &$result, $this ] ) ) {
1017 $status->error( $result );
1021 if ( $result === false ) {
1022 $status->merge( $upp->checkUserPassword( $this, $password, $purpose ) );
1024 } elseif ( $result === true ) {
1027 $status->error( $result );
1028 return $status; // the isValidPassword hook set a string $result and returned true
1033 * Given unvalidated user input, return a canonical username, or false if
1034 * the username is invalid.
1035 * @param string $name User input
1036 * @param string|bool $validate Type of validation to use:
1037 * - false No validation
1038 * - 'valid' Valid for batch processes
1039 * - 'usable' Valid for batch processes and login
1040 * - 'creatable' Valid for batch processes, login and account creation
1042 * @throws InvalidArgumentException
1043 * @return bool|string
1045 public static function getCanonicalName( $name, $validate = 'valid' ) {
1046 // Force usernames to capital
1048 $name = $wgContLang->ucfirst( $name );
1050 # Reject names containing '#'; these will be cleaned up
1051 # with title normalisation, but then it's too late to
1053 if ( strpos( $name, '#' ) !== false ) {
1057 // Clean up name according to title rules,
1058 // but only when validation is requested (bug 12654)
1059 $t = ( $validate !== false ) ?
1060 Title
::newFromText( $name, NS_USER
) : Title
::makeTitle( NS_USER
, $name );
1061 // Check for invalid titles
1062 if ( is_null( $t ) ||
$t->getNamespace() !== NS_USER ||
$t->isExternal() ) {
1066 // Reject various classes of invalid names
1067 $name = AuthManager
::callLegacyAuthPlugin(
1068 'getCanonicalName', [ $t->getText() ], $t->getText()
1071 switch ( $validate ) {
1075 if ( !User
::isValidUserName( $name ) ) {
1080 if ( !User
::isUsableName( $name ) ) {
1085 if ( !User
::isCreatableName( $name ) ) {
1090 throw new InvalidArgumentException(
1091 'Invalid parameter value for $validate in ' . __METHOD__
);
1097 * Count the number of edits of a user
1099 * @param int $uid User ID to check
1100 * @return int The user's edit count
1102 * @deprecated since 1.21 in favour of User::getEditCount
1104 public static function edits( $uid ) {
1105 wfDeprecated( __METHOD__
, '1.21' );
1106 $user = self
::newFromId( $uid );
1107 return $user->getEditCount();
1111 * Return a random password.
1113 * @deprecated since 1.27, use PasswordFactory::generateRandomPasswordString()
1114 * @return string New random password
1116 public static function randomPassword() {
1117 global $wgMinimalPasswordLength;
1118 return PasswordFactory
::generateRandomPasswordString( $wgMinimalPasswordLength );
1122 * Set cached properties to default.
1124 * @note This no longer clears uncached lazy-initialised properties;
1125 * the constructor does that instead.
1127 * @param string|bool $name
1129 public function loadDefaults( $name = false ) {
1131 $this->mName
= $name;
1132 $this->mRealName
= '';
1134 $this->mOptionOverrides
= null;
1135 $this->mOptionsLoaded
= false;
1137 $loggedOut = $this->mRequest
&& !defined( 'MW_NO_SESSION' )
1138 ?
$this->mRequest
->getSession()->getLoggedOutTimestamp() : 0;
1139 if ( $loggedOut !== 0 ) {
1140 $this->mTouched
= wfTimestamp( TS_MW
, $loggedOut );
1142 $this->mTouched
= '1'; # Allow any pages to be cached
1145 $this->mToken
= null; // Don't run cryptographic functions till we need a token
1146 $this->mEmailAuthenticated
= null;
1147 $this->mEmailToken
= '';
1148 $this->mEmailTokenExpires
= null;
1149 $this->mRegistration
= wfTimestamp( TS_MW
);
1150 $this->mGroups
= [];
1152 Hooks
::run( 'UserLoadDefaults', [ $this, $name ] );
1156 * Return whether an item has been loaded.
1158 * @param string $item Item to check. Current possibilities:
1162 * @param string $all 'all' to check if the whole object has been loaded
1163 * or any other string to check if only the item is available (e.g.
1167 public function isItemLoaded( $item, $all = 'all' ) {
1168 return ( $this->mLoadedItems
=== true && $all === 'all' ) ||
1169 ( isset( $this->mLoadedItems
[$item] ) && $this->mLoadedItems
[$item] === true );
1173 * Set that an item has been loaded
1175 * @param string $item
1177 protected function setItemLoaded( $item ) {
1178 if ( is_array( $this->mLoadedItems
) ) {
1179 $this->mLoadedItems
[$item] = true;
1184 * Load user data from the session.
1186 * @return bool True if the user is logged in, false otherwise.
1188 private function loadFromSession() {
1191 Hooks
::run( 'UserLoadFromSession', [ $this, &$result ], '1.27' );
1192 if ( $result !== null ) {
1196 // MediaWiki\Session\Session already did the necessary authentication of the user
1197 // returned here, so just use it if applicable.
1198 $session = $this->getRequest()->getSession();
1199 $user = $session->getUser();
1200 if ( $user->isLoggedIn() ) {
1201 $this->loadFromUserObject( $user );
1202 // Other code expects these to be set in the session, so set them.
1203 $session->set( 'wsUserID', $this->getId() );
1204 $session->set( 'wsUserName', $this->getName() );
1205 $session->set( 'wsToken', $this->getToken() );
1213 * Load user and user_group data from the database.
1214 * $this->mId must be set, this is how the user is identified.
1216 * @param integer $flags User::READ_* constant bitfield
1217 * @return bool True if the user exists, false if the user is anonymous
1219 public function loadFromDatabase( $flags = self
::READ_LATEST
) {
1221 $this->mId
= intval( $this->mId
);
1223 if ( !$this->mId
) {
1224 // Anonymous users are not in the database
1225 $this->loadDefaults();
1229 list( $index, $options ) = DBAccessObjectUtils
::getDBOptions( $flags );
1230 $db = wfGetDB( $index );
1232 $s = $db->selectRow(
1234 self
::selectFields(),
1235 [ 'user_id' => $this->mId
],
1240 $this->queryFlagsUsed
= $flags;
1241 Hooks
::run( 'UserLoadFromDatabase', [ $this, &$s ] );
1243 if ( $s !== false ) {
1244 // Initialise user table data
1245 $this->loadFromRow( $s );
1246 $this->mGroups
= null; // deferred
1247 $this->getEditCount(); // revalidation for nulls
1252 $this->loadDefaults();
1258 * Initialize this object from a row from the user table.
1260 * @param stdClass $row Row from the user table to load.
1261 * @param array $data Further user data to load into the object
1263 * user_groups Array with groups out of the user_groups table
1264 * user_properties Array with properties out of the user_properties table
1266 protected function loadFromRow( $row, $data = null ) {
1269 $this->mGroups
= null; // deferred
1271 if ( isset( $row->user_name
) ) {
1272 $this->mName
= $row->user_name
;
1273 $this->mFrom
= 'name';
1274 $this->setItemLoaded( 'name' );
1279 if ( isset( $row->user_real_name
) ) {
1280 $this->mRealName
= $row->user_real_name
;
1281 $this->setItemLoaded( 'realname' );
1286 if ( isset( $row->user_id
) ) {
1287 $this->mId
= intval( $row->user_id
);
1288 $this->mFrom
= 'id';
1289 $this->setItemLoaded( 'id' );
1294 if ( isset( $row->user_id
) && isset( $row->user_name
) ) {
1295 self
::$idCacheByName[$row->user_name
] = $row->user_id
;
1298 if ( isset( $row->user_editcount
) ) {
1299 $this->mEditCount
= $row->user_editcount
;
1304 if ( isset( $row->user_touched
) ) {
1305 $this->mTouched
= wfTimestamp( TS_MW
, $row->user_touched
);
1310 if ( isset( $row->user_token
) ) {
1311 // The definition for the column is binary(32), so trim the NULs
1312 // that appends. The previous definition was char(32), so trim
1314 $this->mToken
= rtrim( $row->user_token
, " \0" );
1315 if ( $this->mToken
=== '' ) {
1316 $this->mToken
= null;
1322 if ( isset( $row->user_email
) ) {
1323 $this->mEmail
= $row->user_email
;
1324 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
1325 $this->mEmailToken
= $row->user_email_token
;
1326 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
1327 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
1333 $this->mLoadedItems
= true;
1336 if ( is_array( $data ) ) {
1337 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1338 $this->mGroups
= $data['user_groups'];
1340 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1341 $this->loadOptions( $data['user_properties'] );
1347 * Load the data for this user object from another user object.
1351 protected function loadFromUserObject( $user ) {
1353 foreach ( self
::$mCacheVars as $var ) {
1354 $this->$var = $user->$var;
1359 * Load the groups from the database if they aren't already loaded.
1361 private function loadGroups() {
1362 if ( is_null( $this->mGroups
) ) {
1363 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
1364 ?
wfGetDB( DB_MASTER
)
1365 : wfGetDB( DB_REPLICA
);
1366 $res = $db->select( 'user_groups',
1368 [ 'ug_user' => $this->mId
],
1370 $this->mGroups
= [];
1371 foreach ( $res as $row ) {
1372 $this->mGroups
[] = $row->ug_group
;
1378 * Add the user to the group if he/she meets given criteria.
1380 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1381 * possible to remove manually via Special:UserRights. In such case it
1382 * will not be re-added automatically. The user will also not lose the
1383 * group if they no longer meet the criteria.
1385 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1387 * @return array Array of groups the user has been promoted to.
1389 * @see $wgAutopromoteOnce
1391 public function addAutopromoteOnceGroups( $event ) {
1392 global $wgAutopromoteOnceLogInRC;
1394 if ( wfReadOnly() ||
!$this->getId() ) {
1398 $toPromote = Autopromote
::getAutopromoteOnceGroups( $this, $event );
1399 if ( !count( $toPromote ) ) {
1403 if ( !$this->checkAndSetTouched() ) {
1404 return []; // raced out (bug T48834)
1407 $oldGroups = $this->getGroups(); // previous groups
1408 foreach ( $toPromote as $group ) {
1409 $this->addGroup( $group );
1411 // update groups in external authentication database
1412 Hooks
::run( 'UserGroupsChanged', [ $this, $toPromote, [], false, false ] );
1413 AuthManager
::callLegacyAuthPlugin( 'updateExternalDBGroups', [ $this, $toPromote ] );
1415 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1417 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1418 $logEntry->setPerformer( $this );
1419 $logEntry->setTarget( $this->getUserPage() );
1420 $logEntry->setParameters( [
1421 '4::oldgroups' => $oldGroups,
1422 '5::newgroups' => $newGroups,
1424 $logid = $logEntry->insert();
1425 if ( $wgAutopromoteOnceLogInRC ) {
1426 $logEntry->publish( $logid );
1433 * Builds update conditions. Additional conditions may be added to $conditions to
1434 * protected against race conditions using a compare-and-set (CAS) mechanism
1435 * based on comparing $this->mTouched with the user_touched field.
1437 * @param Database $db
1438 * @param array $conditions WHERE conditions for use with Database::update
1439 * @return array WHERE conditions for use with Database::update
1441 protected function makeUpdateConditions( Database
$db, array $conditions ) {
1442 if ( $this->mTouched
) {
1443 // CAS check: only update if the row wasn't changed sicne it was loaded.
1444 $conditions['user_touched'] = $db->timestamp( $this->mTouched
);
1451 * Bump user_touched if it didn't change since this object was loaded
1453 * On success, the mTouched field is updated.
1454 * The user serialization cache is always cleared.
1456 * @return bool Whether user_touched was actually updated
1459 protected function checkAndSetTouched() {
1462 if ( !$this->mId
) {
1463 return false; // anon
1466 // Get a new user_touched that is higher than the old one
1467 $newTouched = $this->newTouchedTimestamp();
1469 $dbw = wfGetDB( DB_MASTER
);
1470 $dbw->update( 'user',
1471 [ 'user_touched' => $dbw->timestamp( $newTouched ) ],
1472 $this->makeUpdateConditions( $dbw, [
1473 'user_id' => $this->mId
,
1477 $success = ( $dbw->affectedRows() > 0 );
1480 $this->mTouched
= $newTouched;
1481 $this->clearSharedCache();
1483 // Clears on failure too since that is desired if the cache is stale
1484 $this->clearSharedCache( 'refresh' );
1491 * Clear various cached data stored in this object. The cache of the user table
1492 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1494 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1495 * given source. May be "name", "id", "defaults", "session", or false for no reload.
1497 public function clearInstanceCache( $reloadFrom = false ) {
1498 $this->mNewtalk
= -1;
1499 $this->mDatePreference
= null;
1500 $this->mBlockedby
= -1; # Unset
1501 $this->mHash
= false;
1502 $this->mRights
= null;
1503 $this->mEffectiveGroups
= null;
1504 $this->mImplicitGroups
= null;
1505 $this->mGroups
= null;
1506 $this->mOptions
= null;
1507 $this->mOptionsLoaded
= false;
1508 $this->mEditCount
= null;
1510 if ( $reloadFrom ) {
1511 $this->mLoadedItems
= [];
1512 $this->mFrom
= $reloadFrom;
1517 * Combine the language default options with any site-specific options
1518 * and add the default language variants.
1520 * @return array Array of String options
1522 public static function getDefaultOptions() {
1523 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1525 static $defOpt = null;
1526 static $defOptLang = null;
1528 if ( $defOpt !== null && $defOptLang === $wgContLang->getCode() ) {
1529 // $wgContLang does not change (and should not change) mid-request,
1530 // but the unit tests change it anyway, and expect this method to
1531 // return values relevant to the current $wgContLang.
1535 $defOpt = $wgDefaultUserOptions;
1536 // Default language setting
1537 $defOptLang = $wgContLang->getCode();
1538 $defOpt['language'] = $defOptLang;
1539 foreach ( LanguageConverter
::$languagesWithVariants as $langCode ) {
1540 $defOpt[$langCode == $wgContLang->getCode() ?
'variant' : "variant-$langCode"] = $langCode;
1543 // NOTE: don't use SearchEngineConfig::getSearchableNamespaces here,
1544 // since extensions may change the set of searchable namespaces depending
1545 // on user groups/permissions.
1546 foreach ( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
1547 $defOpt['searchNs' . $nsnum] = (boolean
)$val;
1549 $defOpt['skin'] = Skin
::normalizeKey( $wgDefaultSkin );
1551 Hooks
::run( 'UserGetDefaultOptions', [ &$defOpt ] );
1557 * Get a given default option value.
1559 * @param string $opt Name of option to retrieve
1560 * @return string Default option value
1562 public static function getDefaultOption( $opt ) {
1563 $defOpts = self
::getDefaultOptions();
1564 if ( isset( $defOpts[$opt] ) ) {
1565 return $defOpts[$opt];
1572 * Get blocking information
1573 * @param bool $bFromSlave Whether to check the replica DB first.
1574 * To improve performance, non-critical checks are done against replica DBs.
1575 * Check when actually saving should be done against master.
1577 private function getBlockedStatus( $bFromSlave = true ) {
1578 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff;
1580 if ( -1 != $this->mBlockedby
) {
1584 wfDebug( __METHOD__
. ": checking...\n" );
1586 // Initialize data...
1587 // Otherwise something ends up stomping on $this->mBlockedby when
1588 // things get lazy-loaded later, causing false positive block hits
1589 // due to -1 !== 0. Probably session-related... Nothing should be
1590 // overwriting mBlockedby, surely?
1593 # We only need to worry about passing the IP address to the Block generator if the
1594 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1595 # know which IP address they're actually coming from
1597 if ( !$this->isAllowed( 'ipblock-exempt' ) ) {
1598 // $wgUser->getName() only works after the end of Setup.php. Until
1599 // then, assume it's a logged-out user.
1600 $globalUserName = $wgUser->isSafeToLoad()
1601 ?
$wgUser->getName()
1602 : IP
::sanitizeIP( $wgUser->getRequest()->getIP() );
1603 if ( $this->getName() === $globalUserName ) {
1604 $ip = $this->getRequest()->getIP();
1609 $block = Block
::newFromTarget( $this, $ip, !$bFromSlave );
1612 if ( !$block instanceof Block
&& $ip !== null && !in_array( $ip, $wgProxyWhitelist ) ) {
1614 if ( self
::isLocallyBlockedProxy( $ip ) ) {
1616 $block->setBlocker( wfMessage( 'proxyblocker' )->text() );
1617 $block->mReason
= wfMessage( 'proxyblockreason' )->text();
1618 $block->setTarget( $ip );
1619 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1621 $block->setBlocker( wfMessage( 'sorbs' )->text() );
1622 $block->mReason
= wfMessage( 'sorbsreason' )->text();
1623 $block->setTarget( $ip );
1627 // (bug 23343) Apply IP blocks to the contents of XFF headers, if enabled
1628 if ( !$block instanceof Block
1629 && $wgApplyIpBlocksToXff
1631 && !in_array( $ip, $wgProxyWhitelist )
1633 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1634 $xff = array_map( 'trim', explode( ',', $xff ) );
1635 $xff = array_diff( $xff, [ $ip ] );
1636 $xffblocks = Block
::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1637 $block = Block
::chooseBlock( $xffblocks, $xff );
1638 if ( $block instanceof Block
) {
1639 # Mangle the reason to alert the user that the block
1640 # originated from matching the X-Forwarded-For header.
1641 $block->mReason
= wfMessage( 'xffblockreason', $block->mReason
)->text();
1645 if ( $block instanceof Block
) {
1646 wfDebug( __METHOD__
. ": Found block.\n" );
1647 $this->mBlock
= $block;
1648 $this->mBlockedby
= $block->getByName();
1649 $this->mBlockreason
= $block->mReason
;
1650 $this->mHideName
= $block->mHideName
;
1651 $this->mAllowUsertalk
= !$block->prevents( 'editownusertalk' );
1653 $this->mBlockedby
= '';
1654 $this->mHideName
= 0;
1655 $this->mAllowUsertalk
= false;
1659 Hooks
::run( 'GetBlockedStatus', [ &$this ] );
1664 * Whether the given IP is in a DNS blacklist.
1666 * @param string $ip IP to check
1667 * @param bool $checkWhitelist Whether to check the whitelist first
1668 * @return bool True if blacklisted.
1670 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1671 global $wgEnableDnsBlacklist, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1673 if ( !$wgEnableDnsBlacklist ) {
1677 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1681 return $this->inDnsBlacklist( $ip, $wgDnsBlacklistUrls );
1685 * Whether the given IP is in a given DNS blacklist.
1687 * @param string $ip IP to check
1688 * @param string|array $bases Array of Strings: URL of the DNS blacklist
1689 * @return bool True if blacklisted.
1691 public function inDnsBlacklist( $ip, $bases ) {
1694 // @todo FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1695 if ( IP
::isIPv4( $ip ) ) {
1696 // Reverse IP, bug 21255
1697 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1699 foreach ( (array)$bases as $base ) {
1701 // If we have an access key, use that too (ProjectHoneypot, etc.)
1703 if ( is_array( $base ) ) {
1704 if ( count( $base ) >= 2 ) {
1705 // Access key is 1, base URL is 0
1706 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1708 $host = "$ipReversed.{$base[0]}";
1710 $basename = $base[0];
1712 $host = "$ipReversed.$base";
1716 $ipList = gethostbynamel( $host );
1719 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $basename!" );
1723 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $basename." );
1732 * Check if an IP address is in the local proxy list
1738 public static function isLocallyBlockedProxy( $ip ) {
1739 global $wgProxyList;
1741 if ( !$wgProxyList ) {
1745 if ( !is_array( $wgProxyList ) ) {
1746 // Load from the specified file
1747 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1750 if ( !is_array( $wgProxyList ) ) {
1752 } elseif ( array_search( $ip, $wgProxyList ) !== false ) {
1754 } elseif ( array_key_exists( $ip, $wgProxyList ) ) {
1755 // Old-style flipped proxy list
1764 * Is this user subject to rate limiting?
1766 * @return bool True if rate limited
1768 public function isPingLimitable() {
1769 global $wgRateLimitsExcludedIPs;
1770 if ( in_array( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1771 // No other good way currently to disable rate limits
1772 // for specific IPs. :P
1773 // But this is a crappy hack and should die.
1776 return !$this->isAllowed( 'noratelimit' );
1780 * Primitive rate limits: enforce maximum actions per time period
1781 * to put a brake on flooding.
1783 * The method generates both a generic profiling point and a per action one
1784 * (suffix being "-$action".
1786 * @note When using a shared cache like memcached, IP-address
1787 * last-hit counters will be shared across wikis.
1789 * @param string $action Action to enforce; 'edit' if unspecified
1790 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
1791 * @return bool True if a rate limiter was tripped
1793 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1794 // Call the 'PingLimiter' hook
1796 if ( !Hooks
::run( 'PingLimiter', [ &$this, $action, &$result, $incrBy ] ) ) {
1800 global $wgRateLimits;
1801 if ( !isset( $wgRateLimits[$action] ) ) {
1805 $limits = array_merge(
1806 [ '&can-bypass' => true ],
1807 $wgRateLimits[$action]
1810 // Some groups shouldn't trigger the ping limiter, ever
1811 if ( $limits['&can-bypass'] && !$this->isPingLimitable() ) {
1816 $id = $this->getId();
1818 $isNewbie = $this->isNewbie();
1822 if ( isset( $limits['anon'] ) ) {
1823 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1826 // limits for logged-in users
1827 if ( isset( $limits['user'] ) ) {
1828 $userLimit = $limits['user'];
1830 // limits for newbie logged-in users
1831 if ( $isNewbie && isset( $limits['newbie'] ) ) {
1832 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1836 // limits for anons and for newbie logged-in users
1839 if ( isset( $limits['ip'] ) ) {
1840 $ip = $this->getRequest()->getIP();
1841 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1843 // subnet-based limits
1844 if ( isset( $limits['subnet'] ) ) {
1845 $ip = $this->getRequest()->getIP();
1846 $subnet = IP
::getSubnet( $ip );
1847 if ( $subnet !== false ) {
1848 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1853 // Check for group-specific permissions
1854 // If more than one group applies, use the group with the highest limit ratio (max/period)
1855 foreach ( $this->getGroups() as $group ) {
1856 if ( isset( $limits[$group] ) ) {
1857 if ( $userLimit === false
1858 ||
$limits[$group][0] / $limits[$group][1] > $userLimit[0] / $userLimit[1]
1860 $userLimit = $limits[$group];
1865 // Set the user limit key
1866 if ( $userLimit !== false ) {
1867 list( $max, $period ) = $userLimit;
1868 wfDebug( __METHOD__
. ": effective user limit: $max in {$period}s\n" );
1869 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $userLimit;
1872 // ip-based limits for all ping-limitable users
1873 if ( isset( $limits['ip-all'] ) ) {
1874 $ip = $this->getRequest()->getIP();
1875 // ignore if user limit is more permissive
1876 if ( $isNewbie ||
$userLimit === false
1877 ||
$limits['ip-all'][0] / $limits['ip-all'][1] > $userLimit[0] / $userLimit[1] ) {
1878 $keys["mediawiki:limiter:$action:ip-all:$ip"] = $limits['ip-all'];
1882 // subnet-based limits for all ping-limitable users
1883 if ( isset( $limits['subnet-all'] ) ) {
1884 $ip = $this->getRequest()->getIP();
1885 $subnet = IP
::getSubnet( $ip );
1886 if ( $subnet !== false ) {
1887 // ignore if user limit is more permissive
1888 if ( $isNewbie ||
$userLimit === false
1889 ||
$limits['ip-all'][0] / $limits['ip-all'][1]
1890 > $userLimit[0] / $userLimit[1] ) {
1891 $keys["mediawiki:limiter:$action:subnet-all:$subnet"] = $limits['subnet-all'];
1896 $cache = ObjectCache
::getLocalClusterInstance();
1899 foreach ( $keys as $key => $limit ) {
1900 list( $max, $period ) = $limit;
1901 $summary = "(limit $max in {$period}s)";
1902 $count = $cache->get( $key );
1905 if ( $count >= $max ) {
1906 wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
1907 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
1910 wfDebug( __METHOD__
. ": ok. $key at $count $summary\n" );
1913 wfDebug( __METHOD__
. ": adding record for $key $summary\n" );
1914 if ( $incrBy > 0 ) {
1915 $cache->add( $key, 0, intval( $period ) ); // first ping
1918 if ( $incrBy > 0 ) {
1919 $cache->incr( $key, $incrBy );
1927 * Check if user is blocked
1929 * @param bool $bFromSlave Whether to check the replica DB instead of
1930 * the master. Hacked from false due to horrible probs on site.
1931 * @return bool True if blocked, false otherwise
1933 public function isBlocked( $bFromSlave = true ) {
1934 return $this->getBlock( $bFromSlave ) instanceof Block
&& $this->getBlock()->prevents( 'edit' );
1938 * Get the block affecting the user, or null if the user is not blocked
1940 * @param bool $bFromSlave Whether to check the replica DB instead of the master
1941 * @return Block|null
1943 public function getBlock( $bFromSlave = true ) {
1944 $this->getBlockedStatus( $bFromSlave );
1945 return $this->mBlock
instanceof Block ?
$this->mBlock
: null;
1949 * Check if user is blocked from editing a particular article
1951 * @param Title $title Title to check
1952 * @param bool $bFromSlave Whether to check the replica DB instead of the master
1955 public function isBlockedFrom( $title, $bFromSlave = false ) {
1956 global $wgBlockAllowsUTEdit;
1958 $blocked = $this->isBlocked( $bFromSlave );
1959 $allowUsertalk = ( $wgBlockAllowsUTEdit ?
$this->mAllowUsertalk
: false );
1960 // If a user's name is suppressed, they cannot make edits anywhere
1961 if ( !$this->mHideName
&& $allowUsertalk && $title->getText() === $this->getName()
1962 && $title->getNamespace() == NS_USER_TALK
) {
1964 wfDebug( __METHOD__
. ": self-talk page, ignoring any blocks\n" );
1967 Hooks
::run( 'UserIsBlockedFrom', [ $this, $title, &$blocked, &$allowUsertalk ] );
1973 * If user is blocked, return the name of the user who placed the block
1974 * @return string Name of blocker
1976 public function blockedBy() {
1977 $this->getBlockedStatus();
1978 return $this->mBlockedby
;
1982 * If user is blocked, return the specified reason for the block
1983 * @return string Blocking reason
1985 public function blockedFor() {
1986 $this->getBlockedStatus();
1987 return $this->mBlockreason
;
1991 * If user is blocked, return the ID for the block
1992 * @return int Block ID
1994 public function getBlockId() {
1995 $this->getBlockedStatus();
1996 return ( $this->mBlock ?
$this->mBlock
->getId() : false );
2000 * Check if user is blocked on all wikis.
2001 * Do not use for actual edit permission checks!
2002 * This is intended for quick UI checks.
2004 * @param string $ip IP address, uses current client if none given
2005 * @return bool True if blocked, false otherwise
2007 public function isBlockedGlobally( $ip = '' ) {
2008 return $this->getGlobalBlock( $ip ) instanceof Block
;
2012 * Check if user is blocked on all wikis.
2013 * Do not use for actual edit permission checks!
2014 * This is intended for quick UI checks.
2016 * @param string $ip IP address, uses current client if none given
2017 * @return Block|null Block object if blocked, null otherwise
2018 * @throws FatalError
2019 * @throws MWException
2021 public function getGlobalBlock( $ip = '' ) {
2022 if ( $this->mGlobalBlock
!== null ) {
2023 return $this->mGlobalBlock ?
: null;
2025 // User is already an IP?
2026 if ( IP
::isIPAddress( $this->getName() ) ) {
2027 $ip = $this->getName();
2029 $ip = $this->getRequest()->getIP();
2033 Hooks
::run( 'UserIsBlockedGlobally', [ &$this, $ip, &$blocked, &$block ] );
2035 if ( $blocked && $block === null ) {
2036 // back-compat: UserIsBlockedGlobally didn't have $block param first
2038 $block->setTarget( $ip );
2041 $this->mGlobalBlock
= $blocked ?
$block : false;
2042 return $this->mGlobalBlock ?
: null;
2046 * Check if user account is locked
2048 * @return bool True if locked, false otherwise
2050 public function isLocked() {
2051 if ( $this->mLocked
!== null ) {
2052 return $this->mLocked
;
2054 $authUser = AuthManager
::callLegacyAuthPlugin( 'getUserInstance', [ &$this ], null );
2055 $this->mLocked
= $authUser && $authUser->isLocked();
2056 Hooks
::run( 'UserIsLocked', [ $this, &$this->mLocked
] );
2057 return $this->mLocked
;
2061 * Check if user account is hidden
2063 * @return bool True if hidden, false otherwise
2065 public function isHidden() {
2066 if ( $this->mHideName
!== null ) {
2067 return $this->mHideName
;
2069 $this->getBlockedStatus();
2070 if ( !$this->mHideName
) {
2071 $authUser = AuthManager
::callLegacyAuthPlugin( 'getUserInstance', [ &$this ], null );
2072 $this->mHideName
= $authUser && $authUser->isHidden();
2073 Hooks
::run( 'UserIsHidden', [ $this, &$this->mHideName
] );
2075 return $this->mHideName
;
2079 * Get the user's ID.
2080 * @return int The user's ID; 0 if the user is anonymous or nonexistent
2082 public function getId() {
2083 if ( $this->mId
=== null && $this->mName
!== null && User
::isIP( $this->mName
) ) {
2084 // Special case, we know the user is anonymous
2086 } elseif ( !$this->isItemLoaded( 'id' ) ) {
2087 // Don't load if this was initialized from an ID
2091 return (int)$this->mId
;
2095 * Set the user and reload all fields according to a given ID
2096 * @param int $v User ID to reload
2098 public function setId( $v ) {
2100 $this->clearInstanceCache( 'id' );
2104 * Get the user name, or the IP of an anonymous user
2105 * @return string User's name or IP address
2107 public function getName() {
2108 if ( $this->isItemLoaded( 'name', 'only' ) ) {
2109 // Special case optimisation
2110 return $this->mName
;
2113 if ( $this->mName
=== false ) {
2115 $this->mName
= IP
::sanitizeIP( $this->getRequest()->getIP() );
2117 return $this->mName
;
2122 * Set the user name.
2124 * This does not reload fields from the database according to the given
2125 * name. Rather, it is used to create a temporary "nonexistent user" for
2126 * later addition to the database. It can also be used to set the IP
2127 * address for an anonymous user to something other than the current
2130 * @note User::newFromName() has roughly the same function, when the named user
2132 * @param string $str New user name to set
2134 public function setName( $str ) {
2136 $this->mName
= $str;
2140 * Get the user's name escaped by underscores.
2141 * @return string Username escaped by underscores.
2143 public function getTitleKey() {
2144 return str_replace( ' ', '_', $this->getName() );
2148 * Check if the user has new messages.
2149 * @return bool True if the user has new messages
2151 public function getNewtalk() {
2154 // Load the newtalk status if it is unloaded (mNewtalk=-1)
2155 if ( $this->mNewtalk
=== -1 ) {
2156 $this->mNewtalk
= false; # reset talk page status
2158 // Check memcached separately for anons, who have no
2159 // entire User object stored in there.
2160 if ( !$this->mId
) {
2161 global $wgDisableAnonTalk;
2162 if ( $wgDisableAnonTalk ) {
2163 // Anon newtalk disabled by configuration.
2164 $this->mNewtalk
= false;
2166 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName() );
2169 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
2173 return (bool)$this->mNewtalk
;
2177 * Return the data needed to construct links for new talk page message
2178 * alerts. If there are new messages, this will return an associative array
2179 * with the following data:
2180 * wiki: The database name of the wiki
2181 * link: Root-relative link to the user's talk page
2182 * rev: The last talk page revision that the user has seen or null. This
2183 * is useful for building diff links.
2184 * If there are no new messages, it returns an empty array.
2185 * @note This function was designed to accomodate multiple talk pages, but
2186 * currently only returns a single link and revision.
2189 public function getNewMessageLinks() {
2191 if ( !Hooks
::run( 'UserRetrieveNewTalks', [ &$this, &$talks ] ) ) {
2193 } elseif ( !$this->getNewtalk() ) {
2196 $utp = $this->getTalkPage();
2197 $dbr = wfGetDB( DB_REPLICA
);
2198 // Get the "last viewed rev" timestamp from the oldest message notification
2199 $timestamp = $dbr->selectField( 'user_newtalk',
2200 'MIN(user_last_timestamp)',
2201 $this->isAnon() ?
[ 'user_ip' => $this->getName() ] : [ 'user_id' => $this->getId() ],
2203 $rev = $timestamp ? Revision
::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2204 return [ [ 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ] ];
2208 * Get the revision ID for the last talk page revision viewed by the talk
2210 * @return int|null Revision ID or null
2212 public function getNewMessageRevisionId() {
2213 $newMessageRevisionId = null;
2214 $newMessageLinks = $this->getNewMessageLinks();
2215 if ( $newMessageLinks ) {
2216 // Note: getNewMessageLinks() never returns more than a single link
2217 // and it is always for the same wiki, but we double-check here in
2218 // case that changes some time in the future.
2219 if ( count( $newMessageLinks ) === 1
2220 && $newMessageLinks[0]['wiki'] === wfWikiID()
2221 && $newMessageLinks[0]['rev']
2223 /** @var Revision $newMessageRevision */
2224 $newMessageRevision = $newMessageLinks[0]['rev'];
2225 $newMessageRevisionId = $newMessageRevision->getId();
2228 return $newMessageRevisionId;
2232 * Internal uncached check for new messages
2235 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2236 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2237 * @return bool True if the user has new messages
2239 protected function checkNewtalk( $field, $id ) {
2240 $dbr = wfGetDB( DB_REPLICA
);
2242 $ok = $dbr->selectField( 'user_newtalk', $field, [ $field => $id ], __METHOD__
);
2244 return $ok !== false;
2248 * Add or update the new messages flag
2249 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2250 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2251 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2252 * @return bool True if successful, false otherwise
2254 protected function updateNewtalk( $field, $id, $curRev = null ) {
2255 // Get timestamp of the talk page revision prior to the current one
2256 $prevRev = $curRev ?
$curRev->getPrevious() : false;
2257 $ts = $prevRev ?
$prevRev->getTimestamp() : null;
2258 // Mark the user as having new messages since this revision
2259 $dbw = wfGetDB( DB_MASTER
);
2260 $dbw->insert( 'user_newtalk',
2261 [ $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ],
2264 if ( $dbw->affectedRows() ) {
2265 wfDebug( __METHOD__
. ": set on ($field, $id)\n" );
2268 wfDebug( __METHOD__
. " already set ($field, $id)\n" );
2274 * Clear the new messages flag for the given user
2275 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2276 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2277 * @return bool True if successful, false otherwise
2279 protected function deleteNewtalk( $field, $id ) {
2280 $dbw = wfGetDB( DB_MASTER
);
2281 $dbw->delete( 'user_newtalk',
2284 if ( $dbw->affectedRows() ) {
2285 wfDebug( __METHOD__
. ": killed on ($field, $id)\n" );
2288 wfDebug( __METHOD__
. ": already gone ($field, $id)\n" );
2294 * Update the 'You have new messages!' status.
2295 * @param bool $val Whether the user has new messages
2296 * @param Revision $curRev New, as yet unseen revision of the user talk
2297 * page. Ignored if null or !$val.
2299 public function setNewtalk( $val, $curRev = null ) {
2300 if ( wfReadOnly() ) {
2305 $this->mNewtalk
= $val;
2307 if ( $this->isAnon() ) {
2309 $id = $this->getName();
2312 $id = $this->getId();
2316 $changed = $this->updateNewtalk( $field, $id, $curRev );
2318 $changed = $this->deleteNewtalk( $field, $id );
2322 $this->invalidateCache();
2327 * Generate a current or new-future timestamp to be stored in the
2328 * user_touched field when we update things.
2329 * @return string Timestamp in TS_MW format
2331 private function newTouchedTimestamp() {
2332 global $wgClockSkewFudge;
2334 $time = wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
2335 if ( $this->mTouched
&& $time <= $this->mTouched
) {
2336 $time = wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $this->mTouched
) +
1 );
2343 * Clear user data from memcached
2345 * Use after applying updates to the database; caller's
2346 * responsibility to update user_touched if appropriate.
2348 * Called implicitly from invalidateCache() and saveSettings().
2350 * @param string $mode Use 'refresh' to clear now; otherwise before DB commit
2352 public function clearSharedCache( $mode = 'changed' ) {
2353 if ( !$this->getId() ) {
2357 $cache = ObjectCache
::getMainWANInstance();
2358 $key = $this->getCacheKey( $cache );
2359 if ( $mode === 'refresh' ) {
2360 $cache->delete( $key, 1 );
2362 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle(
2363 function() use ( $cache, $key ) {
2364 $cache->delete( $key );
2372 * Immediately touch the user data cache for this account
2374 * Calls touch() and removes account data from memcached
2376 public function invalidateCache() {
2378 $this->clearSharedCache();
2382 * Update the "touched" timestamp for the user
2384 * This is useful on various login/logout events when making sure that
2385 * a browser or proxy that has multiple tenants does not suffer cache
2386 * pollution where the new user sees the old users content. The value
2387 * of getTouched() is checked when determining 304 vs 200 responses.
2388 * Unlike invalidateCache(), this preserves the User object cache and
2389 * avoids database writes.
2393 public function touch() {
2394 $id = $this->getId();
2396 $key = wfMemcKey( 'user-quicktouched', 'id', $id );
2397 ObjectCache
::getMainWANInstance()->touchCheckKey( $key );
2398 $this->mQuickTouched
= null;
2403 * Validate the cache for this account.
2404 * @param string $timestamp A timestamp in TS_MW format
2407 public function validateCache( $timestamp ) {
2408 return ( $timestamp >= $this->getTouched() );
2412 * Get the user touched timestamp
2414 * Use this value only to validate caches via inequalities
2415 * such as in the case of HTTP If-Modified-Since response logic
2417 * @return string TS_MW Timestamp
2419 public function getTouched() {
2423 if ( $this->mQuickTouched
=== null ) {
2424 $key = wfMemcKey( 'user-quicktouched', 'id', $this->mId
);
2425 $cache = ObjectCache
::getMainWANInstance();
2427 $this->mQuickTouched
= wfTimestamp( TS_MW
, $cache->getCheckKeyTime( $key ) );
2430 return max( $this->mTouched
, $this->mQuickTouched
);
2433 return $this->mTouched
;
2437 * Get the user_touched timestamp field (time of last DB updates)
2438 * @return string TS_MW Timestamp
2441 public function getDBTouched() {
2444 return $this->mTouched
;
2448 * @deprecated Removed in 1.27.
2452 public function getPassword() {
2453 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2457 * @deprecated Removed in 1.27.
2461 public function getTemporaryPassword() {
2462 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2466 * Set the password and reset the random token.
2467 * Calls through to authentication plugin if necessary;
2468 * will have no effect if the auth plugin refuses to
2469 * pass the change through or if the legal password
2472 * As a special case, setting the password to null
2473 * wipes it, so the account cannot be logged in until
2474 * a new password is set, for instance via e-mail.
2476 * @deprecated since 1.27, use AuthManager instead
2477 * @param string $str New password to set
2478 * @throws PasswordError On failure
2481 public function setPassword( $str ) {
2482 return $this->setPasswordInternal( $str );
2486 * Set the password and reset the random token unconditionally.
2488 * @deprecated since 1.27, use AuthManager instead
2489 * @param string|null $str New password to set or null to set an invalid
2490 * password hash meaning that the user will not be able to log in
2491 * through the web interface.
2493 public function setInternalPassword( $str ) {
2494 $this->setPasswordInternal( $str );
2498 * Actually set the password and such
2499 * @since 1.27 cannot set a password for a user not in the database
2500 * @param string|null $str New password to set or null to set an invalid
2501 * password hash meaning that the user will not be able to log in
2502 * through the web interface.
2503 * @return bool Success
2505 private function setPasswordInternal( $str ) {
2506 $manager = AuthManager
::singleton();
2508 // If the user doesn't exist yet, fail
2509 if ( !$manager->userExists( $this->getName() ) ) {
2510 throw new LogicException( 'Cannot set a password for a user that is not in the database.' );
2513 $status = $this->changeAuthenticationData( [
2514 'username' => $this->getName(),
2518 if ( !$status->isGood() ) {
2519 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authentication' )
2520 ->info( __METHOD__
. ': Password change rejected: '
2521 . $status->getWikiText( null, null, 'en' ) );
2525 $this->setOption( 'watchlisttoken', false );
2526 SessionManager
::singleton()->invalidateSessionsForUser( $this );
2532 * Changes credentials of the user.
2534 * This is a convenience wrapper around AuthManager::changeAuthenticationData.
2535 * Note that this can return a status that isOK() but not isGood() on certain types of failures,
2536 * e.g. when no provider handled the change.
2538 * @param array $data A set of authentication data in fieldname => value format. This is the
2539 * same data you would pass the changeauthenticationdata API - 'username', 'password' etc.
2543 public function changeAuthenticationData( array $data ) {
2544 $manager = AuthManager
::singleton();
2545 $reqs = $manager->getAuthenticationRequests( AuthManager
::ACTION_CHANGE
, $this );
2546 $reqs = AuthenticationRequest
::loadRequestsFromSubmission( $reqs, $data );
2548 $status = Status
::newGood( 'ignored' );
2549 foreach ( $reqs as $req ) {
2550 $status->merge( $manager->allowsAuthenticationDataChange( $req ), true );
2552 if ( $status->getValue() === 'ignored' ) {
2553 $status->warning( 'authenticationdatachange-ignored' );
2556 if ( $status->isGood() ) {
2557 foreach ( $reqs as $req ) {
2558 $manager->changeAuthenticationData( $req );
2565 * Get the user's current token.
2566 * @param bool $forceCreation Force the generation of a new token if the
2567 * user doesn't have one (default=true for backwards compatibility).
2568 * @return string|null Token
2570 public function getToken( $forceCreation = true ) {
2571 global $wgAuthenticationTokenVersion;
2574 if ( !$this->mToken
&& $forceCreation ) {
2578 if ( !$this->mToken
) {
2579 // The user doesn't have a token, return null to indicate that.
2581 } elseif ( $this->mToken
=== self
::INVALID_TOKEN
) {
2582 // We return a random value here so existing token checks are very
2584 return MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2585 } elseif ( $wgAuthenticationTokenVersion === null ) {
2586 // $wgAuthenticationTokenVersion not in use, so return the raw secret
2587 return $this->mToken
;
2589 // $wgAuthenticationTokenVersion in use, so hmac it.
2590 $ret = MWCryptHash
::hmac( $wgAuthenticationTokenVersion, $this->mToken
, false );
2592 // The raw hash can be overly long. Shorten it up.
2593 $len = max( 32, self
::TOKEN_LENGTH
);
2594 if ( strlen( $ret ) < $len ) {
2595 // Should never happen, even md5 is 128 bits
2596 throw new \
UnexpectedValueException( 'Hmac returned less than 128 bits' );
2598 return substr( $ret, -$len );
2603 * Set the random token (used for persistent authentication)
2604 * Called from loadDefaults() among other places.
2606 * @param string|bool $token If specified, set the token to this value
2608 public function setToken( $token = false ) {
2610 if ( $this->mToken
=== self
::INVALID_TOKEN
) {
2611 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
2612 ->debug( __METHOD__
. ": Ignoring attempt to set token for system user \"$this\"" );
2613 } elseif ( !$token ) {
2614 $this->mToken
= MWCryptRand
::generateHex( self
::TOKEN_LENGTH
);
2616 $this->mToken
= $token;
2621 * Set the password for a password reminder or new account email
2623 * @deprecated Removed in 1.27. Use PasswordReset instead.
2624 * @param string $str New password to set or null to set an invalid
2625 * password hash meaning that the user will not be able to use it
2626 * @param bool $throttle If true, reset the throttle timestamp to the present
2628 public function setNewpassword( $str, $throttle = true ) {
2629 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2633 * Has password reminder email been sent within the last
2634 * $wgPasswordReminderResendTime hours?
2635 * @deprecated Removed in 1.27. See above.
2638 public function isPasswordReminderThrottled() {
2639 throw new BadMethodCallException( __METHOD__
. ' has been removed in 1.27' );
2643 * Get the user's e-mail address
2644 * @return string User's email address
2646 public function getEmail() {
2648 Hooks
::run( 'UserGetEmail', [ $this, &$this->mEmail
] );
2649 return $this->mEmail
;
2653 * Get the timestamp of the user's e-mail authentication
2654 * @return string TS_MW timestamp
2656 public function getEmailAuthenticationTimestamp() {
2658 Hooks
::run( 'UserGetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated
] );
2659 return $this->mEmailAuthenticated
;
2663 * Set the user's e-mail address
2664 * @param string $str New e-mail address
2666 public function setEmail( $str ) {
2668 if ( $str == $this->mEmail
) {
2671 $this->invalidateEmail();
2672 $this->mEmail
= $str;
2673 Hooks
::run( 'UserSetEmail', [ $this, &$this->mEmail
] );
2677 * Set the user's e-mail address and a confirmation mail if needed.
2680 * @param string $str New e-mail address
2683 public function setEmailWithConfirmation( $str ) {
2684 global $wgEnableEmail, $wgEmailAuthentication;
2686 if ( !$wgEnableEmail ) {
2687 return Status
::newFatal( 'emaildisabled' );
2690 $oldaddr = $this->getEmail();
2691 if ( $str === $oldaddr ) {
2692 return Status
::newGood( true );
2695 $type = $oldaddr != '' ?
'changed' : 'set';
2696 $notificationResult = null;
2698 if ( $wgEmailAuthentication ) {
2699 // Send the user an email notifying the user of the change in registered
2700 // email address on their previous email address
2701 if ( $type == 'changed' ) {
2702 $change = $str != '' ?
'changed' : 'removed';
2703 $notificationResult = $this->sendMail(
2704 wfMessage( 'notificationemail_subject_' . $change )->text(),
2705 wfMessage( 'notificationemail_body_' . $change,
2706 $this->getRequest()->getIP(),
2713 $this->setEmail( $str );
2715 if ( $str !== '' && $wgEmailAuthentication ) {
2716 // Send a confirmation request to the new address if needed
2717 $result = $this->sendConfirmationMail( $type );
2719 if ( $notificationResult !== null ) {
2720 $result->merge( $notificationResult );
2723 if ( $result->isGood() ) {
2724 // Say to the caller that a confirmation and notification mail has been sent
2725 $result->value
= 'eauth';
2728 $result = Status
::newGood( true );
2735 * Get the user's real name
2736 * @return string User's real name
2738 public function getRealName() {
2739 if ( !$this->isItemLoaded( 'realname' ) ) {
2743 return $this->mRealName
;
2747 * Set the user's real name
2748 * @param string $str New real name
2750 public function setRealName( $str ) {
2752 $this->mRealName
= $str;
2756 * Get the user's current setting for a given option.
2758 * @param string $oname The option to check
2759 * @param string $defaultOverride A default value returned if the option does not exist
2760 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2761 * @return string User's current value for the option
2762 * @see getBoolOption()
2763 * @see getIntOption()
2765 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2766 global $wgHiddenPrefs;
2767 $this->loadOptions();
2769 # We want 'disabled' preferences to always behave as the default value for
2770 # users, even if they have set the option explicitly in their settings (ie they
2771 # set it, and then it was disabled removing their ability to change it). But
2772 # we don't want to erase the preferences in the database in case the preference
2773 # is re-enabled again. So don't touch $mOptions, just override the returned value
2774 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2775 return self
::getDefaultOption( $oname );
2778 if ( array_key_exists( $oname, $this->mOptions
) ) {
2779 return $this->mOptions
[$oname];
2781 return $defaultOverride;
2786 * Get all user's options
2788 * @param int $flags Bitwise combination of:
2789 * User::GETOPTIONS_EXCLUDE_DEFAULTS Exclude user options that are set
2790 * to the default value. (Since 1.25)
2793 public function getOptions( $flags = 0 ) {
2794 global $wgHiddenPrefs;
2795 $this->loadOptions();
2796 $options = $this->mOptions
;
2798 # We want 'disabled' preferences to always behave as the default value for
2799 # users, even if they have set the option explicitly in their settings (ie they
2800 # set it, and then it was disabled removing their ability to change it). But
2801 # we don't want to erase the preferences in the database in case the preference
2802 # is re-enabled again. So don't touch $mOptions, just override the returned value
2803 foreach ( $wgHiddenPrefs as $pref ) {
2804 $default = self
::getDefaultOption( $pref );
2805 if ( $default !== null ) {
2806 $options[$pref] = $default;
2810 if ( $flags & self
::GETOPTIONS_EXCLUDE_DEFAULTS
) {
2811 $options = array_diff_assoc( $options, self
::getDefaultOptions() );
2818 * Get the user's current setting for a given option, as a boolean value.
2820 * @param string $oname The option to check
2821 * @return bool User's current value for the option
2824 public function getBoolOption( $oname ) {
2825 return (bool)$this->getOption( $oname );
2829 * Get the user's current setting for a given option, as an integer value.
2831 * @param string $oname The option to check
2832 * @param int $defaultOverride A default value returned if the option does not exist
2833 * @return int User's current value for the option
2836 public function getIntOption( $oname, $defaultOverride = 0 ) {
2837 $val = $this->getOption( $oname );
2839 $val = $defaultOverride;
2841 return intval( $val );
2845 * Set the given option for a user.
2847 * You need to call saveSettings() to actually write to the database.
2849 * @param string $oname The option to set
2850 * @param mixed $val New value to set
2852 public function setOption( $oname, $val ) {
2853 $this->loadOptions();
2855 // Explicitly NULL values should refer to defaults
2856 if ( is_null( $val ) ) {
2857 $val = self
::getDefaultOption( $oname );
2860 $this->mOptions
[$oname] = $val;
2864 * Get a token stored in the preferences (like the watchlist one),
2865 * resetting it if it's empty (and saving changes).
2867 * @param string $oname The option name to retrieve the token from
2868 * @return string|bool User's current value for the option, or false if this option is disabled.
2869 * @see resetTokenFromOption()
2871 * @deprecated since 1.26 Applications should use the OAuth extension
2873 public function getTokenFromOption( $oname ) {
2874 global $wgHiddenPrefs;
2876 $id = $this->getId();
2877 if ( !$id ||
in_array( $oname, $wgHiddenPrefs ) ) {
2881 $token = $this->getOption( $oname );
2883 // Default to a value based on the user token to avoid space
2884 // wasted on storing tokens for all users. When this option
2885 // is set manually by the user, only then is it stored.
2886 $token = hash_hmac( 'sha1', "$oname:$id", $this->getToken() );
2893 * Reset a token stored in the preferences (like the watchlist one).
2894 * *Does not* save user's preferences (similarly to setOption()).
2896 * @param string $oname The option name to reset the token in
2897 * @return string|bool New token value, or false if this option is disabled.
2898 * @see getTokenFromOption()
2901 public function resetTokenFromOption( $oname ) {
2902 global $wgHiddenPrefs;
2903 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2907 $token = MWCryptRand
::generateHex( 40 );
2908 $this->setOption( $oname, $token );
2913 * Return a list of the types of user options currently returned by
2914 * User::getOptionKinds().
2916 * Currently, the option kinds are:
2917 * - 'registered' - preferences which are registered in core MediaWiki or
2918 * by extensions using the UserGetDefaultOptions hook.
2919 * - 'registered-multiselect' - as above, using the 'multiselect' type.
2920 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
2921 * - 'userjs' - preferences with names starting with 'userjs-', intended to
2922 * be used by user scripts.
2923 * - 'special' - "preferences" that are not accessible via User::getOptions
2924 * or User::setOptions.
2925 * - 'unused' - preferences about which MediaWiki doesn't know anything.
2926 * These are usually legacy options, removed in newer versions.
2928 * The API (and possibly others) use this function to determine the possible
2929 * option types for validation purposes, so make sure to update this when a
2930 * new option kind is added.
2932 * @see User::getOptionKinds
2933 * @return array Option kinds
2935 public static function listOptionKinds() {
2938 'registered-multiselect',
2939 'registered-checkmatrix',
2947 * Return an associative array mapping preferences keys to the kind of a preference they're
2948 * used for. Different kinds are handled differently when setting or reading preferences.
2950 * See User::listOptionKinds for the list of valid option types that can be provided.
2952 * @see User::listOptionKinds
2953 * @param IContextSource $context
2954 * @param array $options Assoc. array with options keys to check as keys.
2955 * Defaults to $this->mOptions.
2956 * @return array The key => kind mapping data
2958 public function getOptionKinds( IContextSource
$context, $options = null ) {
2959 $this->loadOptions();
2960 if ( $options === null ) {
2961 $options = $this->mOptions
;
2964 $prefs = Preferences
::getPreferences( $this, $context );
2967 // Pull out the "special" options, so they don't get converted as
2968 // multiselect or checkmatrix.
2969 $specialOptions = array_fill_keys( Preferences
::getSaveBlacklist(), true );
2970 foreach ( $specialOptions as $name => $value ) {
2971 unset( $prefs[$name] );
2974 // Multiselect and checkmatrix options are stored in the database with
2975 // one key per option, each having a boolean value. Extract those keys.
2976 $multiselectOptions = [];
2977 foreach ( $prefs as $name => $info ) {
2978 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
2979 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
2980 $opts = HTMLFormField
::flattenOptions( $info['options'] );
2981 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
2983 foreach ( $opts as $value ) {
2984 $multiselectOptions["$prefix$value"] = true;
2987 unset( $prefs[$name] );
2990 $checkmatrixOptions = [];
2991 foreach ( $prefs as $name => $info ) {
2992 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
2993 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
2994 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
2995 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
2996 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
2998 foreach ( $columns as $column ) {
2999 foreach ( $rows as $row ) {
3000 $checkmatrixOptions["$prefix$column-$row"] = true;
3004 unset( $prefs[$name] );
3008 // $value is ignored
3009 foreach ( $options as $key => $value ) {
3010 if ( isset( $prefs[$key] ) ) {
3011 $mapping[$key] = 'registered';
3012 } elseif ( isset( $multiselectOptions[$key] ) ) {
3013 $mapping[$key] = 'registered-multiselect';
3014 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
3015 $mapping[$key] = 'registered-checkmatrix';
3016 } elseif ( isset( $specialOptions[$key] ) ) {
3017 $mapping[$key] = 'special';
3018 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
3019 $mapping[$key] = 'userjs';
3021 $mapping[$key] = 'unused';
3029 * Reset certain (or all) options to the site defaults
3031 * The optional parameter determines which kinds of preferences will be reset.
3032 * Supported values are everything that can be reported by getOptionKinds()
3033 * and 'all', which forces a reset of *all* preferences and overrides everything else.
3035 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
3036 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
3037 * for backwards-compatibility.
3038 * @param IContextSource|null $context Context source used when $resetKinds
3039 * does not contain 'all', passed to getOptionKinds().
3040 * Defaults to RequestContext::getMain() when null.
3042 public function resetOptions(
3043 $resetKinds = [ 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ],
3044 IContextSource
$context = null
3047 $defaultOptions = self
::getDefaultOptions();
3049 if ( !is_array( $resetKinds ) ) {
3050 $resetKinds = [ $resetKinds ];
3053 if ( in_array( 'all', $resetKinds ) ) {
3054 $newOptions = $defaultOptions;
3056 if ( $context === null ) {
3057 $context = RequestContext
::getMain();
3060 $optionKinds = $this->getOptionKinds( $context );
3061 $resetKinds = array_intersect( $resetKinds, self
::listOptionKinds() );
3064 // Use default values for the options that should be deleted, and
3065 // copy old values for the ones that shouldn't.
3066 foreach ( $this->mOptions
as $key => $value ) {
3067 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
3068 if ( array_key_exists( $key, $defaultOptions ) ) {
3069 $newOptions[$key] = $defaultOptions[$key];
3072 $newOptions[$key] = $value;
3077 Hooks
::run( 'UserResetAllOptions', [ $this, &$newOptions, $this->mOptions
, $resetKinds ] );
3079 $this->mOptions
= $newOptions;
3080 $this->mOptionsLoaded
= true;
3084 * Get the user's preferred date format.
3085 * @return string User's preferred date format
3087 public function getDatePreference() {
3088 // Important migration for old data rows
3089 if ( is_null( $this->mDatePreference
) ) {
3091 $value = $this->getOption( 'date' );
3092 $map = $wgLang->getDatePreferenceMigrationMap();
3093 if ( isset( $map[$value] ) ) {
3094 $value = $map[$value];
3096 $this->mDatePreference
= $value;
3098 return $this->mDatePreference
;
3102 * Determine based on the wiki configuration and the user's options,
3103 * whether this user must be over HTTPS no matter what.
3107 public function requiresHTTPS() {
3108 global $wgSecureLogin;
3109 if ( !$wgSecureLogin ) {
3112 $https = $this->getBoolOption( 'prefershttps' );
3113 Hooks
::run( 'UserRequiresHTTPS', [ $this, &$https ] );
3115 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
3122 * Get the user preferred stub threshold
3126 public function getStubThreshold() {
3127 global $wgMaxArticleSize; # Maximum article size, in Kb
3128 $threshold = $this->getIntOption( 'stubthreshold' );
3129 if ( $threshold > $wgMaxArticleSize * 1024 ) {
3130 // If they have set an impossible value, disable the preference
3131 // so we can use the parser cache again.
3138 * Get the permissions this user has.
3139 * @return array Array of String permission names
3141 public function getRights() {
3142 if ( is_null( $this->mRights
) ) {
3143 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
3144 Hooks
::run( 'UserGetRights', [ $this, &$this->mRights
] );
3146 // Deny any rights denied by the user's session, unless this
3147 // endpoint has no sessions.
3148 if ( !defined( 'MW_NO_SESSION' ) ) {
3149 $allowedRights = $this->getRequest()->getSession()->getAllowedUserRights();
3150 if ( $allowedRights !== null ) {
3151 $this->mRights
= array_intersect( $this->mRights
, $allowedRights );
3155 // Force reindexation of rights when a hook has unset one of them
3156 $this->mRights
= array_values( array_unique( $this->mRights
) );
3158 // If block disables login, we should also remove any
3159 // extra rights blocked users might have, in case the
3160 // blocked user has a pre-existing session (T129738).
3161 // This is checked here for cases where people only call
3162 // $user->isAllowed(). It is also checked in Title::checkUserBlock()
3163 // to give a better error message in the common case.
3164 $config = RequestContext
::getMain()->getConfig();
3166 $this->isLoggedIn() &&
3167 $config->get( 'BlockDisablesLogin' ) &&
3171 $this->mRights
= array_intersect( $this->mRights
, $anon->getRights() );
3174 return $this->mRights
;
3178 * Get the list of explicit group memberships this user has.
3179 * The implicit * and user groups are not included.
3180 * @return array Array of String internal group names
3182 public function getGroups() {
3184 $this->loadGroups();
3185 return $this->mGroups
;
3189 * Get the list of implicit group memberships this user has.
3190 * This includes all explicit groups, plus 'user' if logged in,
3191 * '*' for all accounts, and autopromoted groups
3192 * @param bool $recache Whether to avoid the cache
3193 * @return array Array of String internal group names
3195 public function getEffectiveGroups( $recache = false ) {
3196 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
3197 $this->mEffectiveGroups
= array_unique( array_merge(
3198 $this->getGroups(), // explicit groups
3199 $this->getAutomaticGroups( $recache ) // implicit groups
3201 // Hook for additional groups
3202 Hooks
::run( 'UserEffectiveGroups', [ &$this, &$this->mEffectiveGroups
] );
3203 // Force reindexation of groups when a hook has unset one of them
3204 $this->mEffectiveGroups
= array_values( array_unique( $this->mEffectiveGroups
) );
3206 return $this->mEffectiveGroups
;
3210 * Get the list of implicit group memberships this user has.
3211 * This includes 'user' if logged in, '*' for all accounts,
3212 * and autopromoted groups
3213 * @param bool $recache Whether to avoid the cache
3214 * @return array Array of String internal group names
3216 public function getAutomaticGroups( $recache = false ) {
3217 if ( $recache ||
is_null( $this->mImplicitGroups
) ) {
3218 $this->mImplicitGroups
= [ '*' ];
3219 if ( $this->getId() ) {
3220 $this->mImplicitGroups
[] = 'user';
3222 $this->mImplicitGroups
= array_unique( array_merge(
3223 $this->mImplicitGroups
,
3224 Autopromote
::getAutopromoteGroups( $this )
3228 // Assure data consistency with rights/groups,
3229 // as getEffectiveGroups() depends on this function
3230 $this->mEffectiveGroups
= null;
3233 return $this->mImplicitGroups
;
3237 * Returns the groups the user has belonged to.
3239 * The user may still belong to the returned groups. Compare with getGroups().
3241 * The function will not return groups the user had belonged to before MW 1.17
3243 * @return array Names of the groups the user has belonged to.
3245 public function getFormerGroups() {
3248 if ( is_null( $this->mFormerGroups
) ) {
3249 $db = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
3250 ?
wfGetDB( DB_MASTER
)
3251 : wfGetDB( DB_REPLICA
);
3252 $res = $db->select( 'user_former_groups',
3254 [ 'ufg_user' => $this->mId
],
3256 $this->mFormerGroups
= [];
3257 foreach ( $res as $row ) {
3258 $this->mFormerGroups
[] = $row->ufg_group
;
3262 return $this->mFormerGroups
;
3266 * Get the user's edit count.
3267 * @return int|null Null for anonymous users
3269 public function getEditCount() {
3270 if ( !$this->getId() ) {
3274 if ( $this->mEditCount
=== null ) {
3275 /* Populate the count, if it has not been populated yet */
3276 $dbr = wfGetDB( DB_REPLICA
);
3277 // check if the user_editcount field has been initialized
3278 $count = $dbr->selectField(
3279 'user', 'user_editcount',
3280 [ 'user_id' => $this->mId
],
3284 if ( $count === null ) {
3285 // it has not been initialized. do so.
3286 $count = $this->initEditCount();
3288 $this->mEditCount
= $count;
3290 return (int)$this->mEditCount
;
3294 * Add the user to the given group.
3295 * This takes immediate effect.
3296 * @param string $group Name of the group to add
3299 public function addGroup( $group ) {
3302 if ( !Hooks
::run( 'UserAddGroup', [ $this, &$group ] ) ) {
3306 $dbw = wfGetDB( DB_MASTER
);
3307 if ( $this->getId() ) {
3308 $dbw->insert( 'user_groups',
3310 'ug_user' => $this->getId(),
3311 'ug_group' => $group,
3317 $this->loadGroups();
3318 $this->mGroups
[] = $group;
3319 // In case loadGroups was not called before, we now have the right twice.
3320 // Get rid of the duplicate.
3321 $this->mGroups
= array_unique( $this->mGroups
);
3323 // Refresh the groups caches, and clear the rights cache so it will be
3324 // refreshed on the next call to $this->getRights().
3325 $this->getEffectiveGroups( true );
3326 $this->mRights
= null;
3328 $this->invalidateCache();
3334 * Remove the user from the given group.
3335 * This takes immediate effect.
3336 * @param string $group Name of the group to remove
3339 public function removeGroup( $group ) {
3341 if ( !Hooks
::run( 'UserRemoveGroup', [ $this, &$group ] ) ) {
3345 $dbw = wfGetDB( DB_MASTER
);
3346 $dbw->delete( 'user_groups',
3348 'ug_user' => $this->getId(),
3349 'ug_group' => $group,
3352 // Remember that the user was in this group
3353 $dbw->insert( 'user_former_groups',
3355 'ufg_user' => $this->getId(),
3356 'ufg_group' => $group,
3362 $this->loadGroups();
3363 $this->mGroups
= array_diff( $this->mGroups
, [ $group ] );
3365 // Refresh the groups caches, and clear the rights cache so it will be
3366 // refreshed on the next call to $this->getRights().
3367 $this->getEffectiveGroups( true );
3368 $this->mRights
= null;
3370 $this->invalidateCache();
3376 * Get whether the user is logged in
3379 public function isLoggedIn() {
3380 return $this->getId() != 0;
3384 * Get whether the user is anonymous
3387 public function isAnon() {
3388 return !$this->isLoggedIn();
3392 * @return bool Whether this user is flagged as being a bot role account
3395 public function isBot() {
3396 if ( in_array( 'bot', $this->getGroups() ) && $this->isAllowed( 'bot' ) ) {
3401 Hooks
::run( "UserIsBot", [ $this, &$isBot ] );
3407 * Check if user is allowed to access a feature / make an action
3409 * @param string ... Permissions to test
3410 * @return bool True if user is allowed to perform *any* of the given actions
3412 public function isAllowedAny() {
3413 $permissions = func_get_args();
3414 foreach ( $permissions as $permission ) {
3415 if ( $this->isAllowed( $permission ) ) {
3424 * @param string ... Permissions to test
3425 * @return bool True if the user is allowed to perform *all* of the given actions
3427 public function isAllowedAll() {
3428 $permissions = func_get_args();
3429 foreach ( $permissions as $permission ) {
3430 if ( !$this->isAllowed( $permission ) ) {
3438 * Internal mechanics of testing a permission
3439 * @param string $action
3442 public function isAllowed( $action = '' ) {
3443 if ( $action === '' ) {
3444 return true; // In the spirit of DWIM
3446 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3447 // by misconfiguration: 0 == 'foo'
3448 return in_array( $action, $this->getRights(), true );
3452 * Check whether to enable recent changes patrol features for this user
3453 * @return bool True or false
3455 public function useRCPatrol() {
3456 global $wgUseRCPatrol;
3457 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3461 * Check whether to enable new pages patrol features for this user
3462 * @return bool True or false
3464 public function useNPPatrol() {
3465 global $wgUseRCPatrol, $wgUseNPPatrol;
3467 ( $wgUseRCPatrol ||
$wgUseNPPatrol )
3468 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3473 * Check whether to enable new files patrol features for this user
3474 * @return bool True or false
3476 public function useFilePatrol() {
3477 global $wgUseRCPatrol, $wgUseFilePatrol;
3479 ( $wgUseRCPatrol ||
$wgUseFilePatrol )
3480 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3485 * Get the WebRequest object to use with this object
3487 * @return WebRequest
3489 public function getRequest() {
3490 if ( $this->mRequest
) {
3491 return $this->mRequest
;
3499 * Check the watched status of an article.
3500 * @since 1.22 $checkRights parameter added
3501 * @param Title $title Title of the article to look at
3502 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3503 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3506 public function isWatched( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3507 if ( $title->isWatchable() && ( !$checkRights ||
$this->isAllowed( 'viewmywatchlist' ) ) ) {
3508 return MediaWikiServices
::getInstance()->getWatchedItemStore()->isWatched( $this, $title );
3515 * @since 1.22 $checkRights parameter added
3516 * @param Title $title Title of the article to look at
3517 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3518 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3520 public function addWatch( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3521 if ( !$checkRights ||
$this->isAllowed( 'editmywatchlist' ) ) {
3522 MediaWikiServices
::getInstance()->getWatchedItemStore()->addWatchBatchForUser(
3524 [ $title->getSubjectPage(), $title->getTalkPage() ]
3527 $this->invalidateCache();
3531 * Stop watching an article.
3532 * @since 1.22 $checkRights parameter added
3533 * @param Title $title Title of the article to look at
3534 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3535 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3537 public function removeWatch( $title, $checkRights = self
::CHECK_USER_RIGHTS
) {
3538 if ( !$checkRights ||
$this->isAllowed( 'editmywatchlist' ) ) {
3539 $store = MediaWikiServices
::getInstance()->getWatchedItemStore();
3540 $store->removeWatch( $this, $title->getSubjectPage() );
3541 $store->removeWatch( $this, $title->getTalkPage() );
3543 $this->invalidateCache();
3547 * Clear the user's notification timestamp for the given title.
3548 * If e-notif e-mails are on, they will receive notification mails on
3549 * the next change of the page if it's watched etc.
3550 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3551 * @param Title $title Title of the article to look at
3552 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3554 public function clearNotification( &$title, $oldid = 0 ) {
3555 global $wgUseEnotif, $wgShowUpdatedMarker;
3557 // Do nothing if the database is locked to writes
3558 if ( wfReadOnly() ) {
3562 // Do nothing if not allowed to edit the watchlist
3563 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3567 // If we're working on user's talk page, we should update the talk page message indicator
3568 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3569 if ( !Hooks
::run( 'UserClearNewTalkNotification', [ &$this, $oldid ] ) ) {
3573 // Try to update the DB post-send and only if needed...
3574 DeferredUpdates
::addCallableUpdate( function() use ( $title, $oldid ) {
3575 if ( !$this->getNewtalk() ) {
3576 return; // no notifications to clear
3579 // Delete the last notifications (they stack up)
3580 $this->setNewtalk( false );
3582 // If there is a new, unseen, revision, use its timestamp
3584 ?
$title->getNextRevisionID( $oldid, Title
::GAID_FOR_UPDATE
)
3587 $this->setNewtalk( true, Revision
::newFromId( $nextid ) );
3592 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3596 if ( $this->isAnon() ) {
3597 // Nothing else to do...
3601 // Only update the timestamp if the page is being watched.
3602 // The query to find out if it is watched is cached both in memcached and per-invocation,
3603 // and when it does have to be executed, it can be on a replica DB
3604 // If this is the user's newtalk page, we always update the timestamp
3606 if ( $title->getNamespace() == NS_USER_TALK
&& $title->getText() == $this->getName() ) {
3610 MediaWikiServices
::getInstance()->getWatchedItemStore()
3611 ->resetNotificationTimestamp( $this, $title, $force, $oldid );
3615 * Resets all of the given user's page-change notification timestamps.
3616 * If e-notif e-mails are on, they will receive notification mails on
3617 * the next change of any watched page.
3618 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3620 public function clearAllNotifications() {
3621 global $wgUseEnotif, $wgShowUpdatedMarker;
3622 // Do nothing if not allowed to edit the watchlist
3623 if ( wfReadOnly() ||
!$this->isAllowed( 'editmywatchlist' ) ) {
3627 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3628 $this->setNewtalk( false );
3632 $id = $this->getId();
3637 $dbw = wfGetDB( DB_MASTER
);
3638 $asOfTimes = array_unique( $dbw->selectFieldValues(
3640 'wl_notificationtimestamp',
3641 [ 'wl_user' => $id, 'wl_notificationtimestamp IS NOT NULL' ],
3643 [ 'ORDER BY' => 'wl_notificationtimestamp DESC', 'LIMIT' => 500 ]
3645 if ( !$asOfTimes ) {
3648 // Immediately update the most recent touched rows, which hopefully covers what
3649 // the user sees on the watchlist page before pressing "mark all pages visited"....
3652 [ 'wl_notificationtimestamp' => null ],
3653 [ 'wl_user' => $id, 'wl_notificationtimestamp' => $asOfTimes ],
3656 // ...and finish the older ones in a post-send update with lag checks...
3657 DeferredUpdates
::addUpdate( new AutoCommitUpdate(
3660 function () use ( $dbw, $id ) {
3661 global $wgUpdateRowsPerQuery;
3663 $lbFactory = MediaWikiServices
::getInstance()->getDBLoadBalancerFactory();
3664 $ticket = $lbFactory->getEmptyTransactionTicket( __METHOD__
);
3665 $asOfTimes = array_unique( $dbw->selectFieldValues(
3667 'wl_notificationtimestamp',
3668 [ 'wl_user' => $id, 'wl_notificationtimestamp IS NOT NULL' ],
3671 foreach ( array_chunk( $asOfTimes, $wgUpdateRowsPerQuery ) as $asOfTimeBatch ) {
3674 [ 'wl_notificationtimestamp' => null ],
3675 [ 'wl_user' => $id, 'wl_notificationtimestamp' => $asOfTimeBatch ],
3678 $lbFactory->commitAndWaitForReplication( __METHOD__
, $ticket );
3682 // We also need to clear here the "you have new message" notification for the own
3683 // user_talk page; it's cleared one page view later in WikiPage::doViewUpdates().
3687 * Set a cookie on the user's client. Wrapper for
3688 * WebResponse::setCookie
3689 * @deprecated since 1.27
3690 * @param string $name Name of the cookie to set
3691 * @param string $value Value to set
3692 * @param int $exp Expiration time, as a UNIX time value;
3693 * if 0 or not specified, use the default $wgCookieExpiration
3694 * @param bool $secure
3695 * true: Force setting the secure attribute when setting the cookie
3696 * false: Force NOT setting the secure attribute when setting the cookie
3697 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3698 * @param array $params Array of options sent passed to WebResponse::setcookie()
3699 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3702 protected function setCookie(
3703 $name, $value, $exp = 0, $secure = null, $params = [], $request = null
3705 wfDeprecated( __METHOD__
, '1.27' );
3706 if ( $request === null ) {
3707 $request = $this->getRequest();
3709 $params['secure'] = $secure;
3710 $request->response()->setCookie( $name, $value, $exp, $params );
3714 * Clear a cookie on the user's client
3715 * @deprecated since 1.27
3716 * @param string $name Name of the cookie to clear
3717 * @param bool $secure
3718 * true: Force setting the secure attribute when setting the cookie
3719 * false: Force NOT setting the secure attribute when setting the cookie
3720 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3721 * @param array $params Array of options sent passed to WebResponse::setcookie()
3723 protected function clearCookie( $name, $secure = null, $params = [] ) {
3724 wfDeprecated( __METHOD__
, '1.27' );
3725 $this->setCookie( $name, '', time() - 86400, $secure, $params );
3729 * Set an extended login cookie on the user's client. The expiry of the cookie
3730 * is controlled by the $wgExtendedLoginCookieExpiration configuration
3733 * @see User::setCookie
3735 * @deprecated since 1.27
3736 * @param string $name Name of the cookie to set
3737 * @param string $value Value to set
3738 * @param bool $secure
3739 * true: Force setting the secure attribute when setting the cookie
3740 * false: Force NOT setting the secure attribute when setting the cookie
3741 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3743 protected function setExtendedLoginCookie( $name, $value, $secure ) {
3744 global $wgExtendedLoginCookieExpiration, $wgCookieExpiration;
3746 wfDeprecated( __METHOD__
, '1.27' );
3749 $exp +
= $wgExtendedLoginCookieExpiration !== null
3750 ?
$wgExtendedLoginCookieExpiration
3751 : $wgCookieExpiration;
3753 $this->setCookie( $name, $value, $exp, $secure );
3757 * Persist this user's session (e.g. set cookies)
3759 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3761 * @param bool $secure Whether to force secure/insecure cookies or use default
3762 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3764 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3766 if ( 0 == $this->mId
) {
3770 $session = $this->getRequest()->getSession();
3771 if ( $request && $session->getRequest() !== $request ) {
3772 $session = $session->sessionWithRequest( $request );
3774 $delay = $session->delaySave();
3776 if ( !$session->getUser()->equals( $this ) ) {
3777 if ( !$session->canSetUser() ) {
3778 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3779 ->warning( __METHOD__
.
3780 ": Cannot save user \"$this\" to a user \"{$session->getUser()}\"'s immutable session"
3784 $session->setUser( $this );
3787 $session->setRememberUser( $rememberMe );
3788 if ( $secure !== null ) {
3789 $session->setForceHTTPS( $secure );
3792 $session->persist();
3794 ScopedCallback
::consume( $delay );
3798 * Log this user out.
3800 public function logout() {
3801 if ( Hooks
::run( 'UserLogout', [ &$this ] ) ) {
3807 * Clear the user's session, and reset the instance cache.
3810 public function doLogout() {
3811 $session = $this->getRequest()->getSession();
3812 if ( !$session->canSetUser() ) {
3813 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3814 ->warning( __METHOD__
. ": Cannot log out of an immutable session" );
3815 $error = 'immutable';
3816 } elseif ( !$session->getUser()->equals( $this ) ) {
3817 \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' )
3818 ->warning( __METHOD__
.
3819 ": Cannot log user \"$this\" out of a user \"{$session->getUser()}\"'s session"
3821 // But we still may as well make this user object anon
3822 $this->clearInstanceCache( 'defaults' );
3823 $error = 'wronguser';
3825 $this->clearInstanceCache( 'defaults' );
3826 $delay = $session->delaySave();
3827 $session->unpersist(); // Clear cookies (T127436)
3828 $session->setLoggedOutTimestamp( time() );
3829 $session->setUser( new User
);
3830 $session->set( 'wsUserID', 0 ); // Other code expects this
3831 $session->resetAllTokens();
3832 ScopedCallback
::consume( $delay );
3835 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authevents' )->info( 'Logout', [
3836 'event' => 'logout',
3837 'successful' => $error === false,
3838 'status' => $error ?
: 'success',
3843 * Save this user's settings into the database.
3844 * @todo Only rarely do all these fields need to be set!
3846 public function saveSettings() {
3847 if ( wfReadOnly() ) {
3848 // @TODO: caller should deal with this instead!
3849 // This should really just be an exception.
3850 MWExceptionHandler
::logException( new DBExpectedError(
3852 "Could not update user with ID '{$this->mId}'; DB is read-only."
3858 if ( 0 == $this->mId
) {
3862 // Get a new user_touched that is higher than the old one.
3863 // This will be used for a CAS check as a last-resort safety
3864 // check against race conditions and replica DB lag.
3865 $newTouched = $this->newTouchedTimestamp();
3867 $dbw = wfGetDB( DB_MASTER
);
3868 $dbw->update( 'user',
3870 'user_name' => $this->mName
,
3871 'user_real_name' => $this->mRealName
,
3872 'user_email' => $this->mEmail
,
3873 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
3874 'user_touched' => $dbw->timestamp( $newTouched ),
3875 'user_token' => strval( $this->mToken
),
3876 'user_email_token' => $this->mEmailToken
,
3877 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
3878 ], $this->makeUpdateConditions( $dbw, [ /* WHERE */
3879 'user_id' => $this->mId
,
3883 if ( !$dbw->affectedRows() ) {
3884 // Maybe the problem was a missed cache update; clear it to be safe
3885 $this->clearSharedCache( 'refresh' );
3886 // User was changed in the meantime or loaded with stale data
3887 $from = ( $this->queryFlagsUsed
& self
::READ_LATEST
) ?
'master' : 'replica';
3888 throw new MWException(
3889 "CAS update failed on user_touched for user ID '{$this->mId}' (read from $from);" .
3890 " the version of the user to be saved is older than the current version."
3894 $this->mTouched
= $newTouched;
3895 $this->saveOptions();
3897 Hooks
::run( 'UserSaveSettings', [ $this ] );
3898 $this->clearSharedCache();
3899 $this->getUserPage()->invalidateCache();
3903 * If only this user's username is known, and it exists, return the user ID.
3905 * @param int $flags Bitfield of User:READ_* constants; useful for existence checks
3908 public function idForName( $flags = 0 ) {
3909 $s = trim( $this->getName() );
3914 $db = ( ( $flags & self
::READ_LATEST
) == self
::READ_LATEST
)
3915 ?
wfGetDB( DB_MASTER
)
3916 : wfGetDB( DB_REPLICA
);
3918 $options = ( ( $flags & self
::READ_LOCKING
) == self
::READ_LOCKING
)
3919 ?
[ 'LOCK IN SHARE MODE' ]
3922 $id = $db->selectField( 'user',
3923 'user_id', [ 'user_name' => $s ], __METHOD__
, $options );
3929 * Add a user to the database, return the user object
3931 * @param string $name Username to add
3932 * @param array $params Array of Strings Non-default parameters to save to
3933 * the database as user_* fields:
3934 * - email: The user's email address.
3935 * - email_authenticated: The email authentication timestamp.
3936 * - real_name: The user's real name.
3937 * - options: An associative array of non-default options.
3938 * - token: Random authentication token. Do not set.
3939 * - registration: Registration timestamp. Do not set.
3941 * @return User|null User object, or null if the username already exists.
3943 public static function createNew( $name, $params = [] ) {
3944 foreach ( [ 'password', 'newpassword', 'newpass_time', 'password_expires' ] as $field ) {
3945 if ( isset( $params[$field] ) ) {
3946 wfDeprecated( __METHOD__
. " with param '$field'", '1.27' );
3947 unset( $params[$field] );
3953 $user->setToken(); // init token
3954 if ( isset( $params['options'] ) ) {
3955 $user->mOptions
= $params['options'] +
(array)$user->mOptions
;
3956 unset( $params['options'] );
3958 $dbw = wfGetDB( DB_MASTER
);
3959 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3961 $noPass = PasswordFactory
::newInvalidPassword()->toString();
3964 'user_id' => $seqVal,
3965 'user_name' => $name,
3966 'user_password' => $noPass,
3967 'user_newpassword' => $noPass,
3968 'user_email' => $user->mEmail
,
3969 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
3970 'user_real_name' => $user->mRealName
,
3971 'user_token' => strval( $user->mToken
),
3972 'user_registration' => $dbw->timestamp( $user->mRegistration
),
3973 'user_editcount' => 0,
3974 'user_touched' => $dbw->timestamp( $user->newTouchedTimestamp() ),
3976 foreach ( $params as $name => $value ) {
3977 $fields["user_$name"] = $value;
3979 $dbw->insert( 'user', $fields, __METHOD__
, [ 'IGNORE' ] );
3980 if ( $dbw->affectedRows() ) {
3981 $newUser = User
::newFromId( $dbw->insertId() );
3989 * Add this existing user object to the database. If the user already
3990 * exists, a fatal status object is returned, and the user object is
3991 * initialised with the data from the database.
3993 * Previously, this function generated a DB error due to a key conflict
3994 * if the user already existed. Many extension callers use this function
3995 * in code along the lines of:
3997 * $user = User::newFromName( $name );
3998 * if ( !$user->isLoggedIn() ) {
3999 * $user->addToDatabase();
4001 * // do something with $user...
4003 * However, this was vulnerable to a race condition (bug 16020). By
4004 * initialising the user object if the user exists, we aim to support this
4005 * calling sequence as far as possible.
4007 * Note that if the user exists, this function will acquire a write lock,
4008 * so it is still advisable to make the call conditional on isLoggedIn(),
4009 * and to commit the transaction after calling.
4011 * @throws MWException
4014 public function addToDatabase() {
4016 if ( !$this->mToken
) {
4017 $this->setToken(); // init token
4020 $this->mTouched
= $this->newTouchedTimestamp();
4022 $noPass = PasswordFactory
::newInvalidPassword()->toString();
4024 $dbw = wfGetDB( DB_MASTER
);
4025 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
4026 $dbw->insert( 'user',
4028 'user_id' => $seqVal,
4029 'user_name' => $this->mName
,
4030 'user_password' => $noPass,
4031 'user_newpassword' => $noPass,
4032 'user_email' => $this->mEmail
,
4033 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
4034 'user_real_name' => $this->mRealName
,
4035 'user_token' => strval( $this->mToken
),
4036 'user_registration' => $dbw->timestamp( $this->mRegistration
),
4037 'user_editcount' => 0,
4038 'user_touched' => $dbw->timestamp( $this->mTouched
),
4042 if ( !$dbw->affectedRows() ) {
4043 // Use locking reads to bypass any REPEATABLE-READ snapshot.
4044 $this->mId
= $dbw->selectField(
4047 [ 'user_name' => $this->mName
],
4049 [ 'LOCK IN SHARE MODE' ]
4053 if ( $this->loadFromDatabase( self
::READ_LOCKING
) ) {
4058 throw new MWException( __METHOD__
. ": hit a key conflict attempting " .
4059 "to insert user '{$this->mName}' row, but it was not present in select!" );
4061 return Status
::newFatal( 'userexists' );
4063 $this->mId
= $dbw->insertId();
4064 self
::$idCacheByName[$this->mName
] = $this->mId
;
4066 // Clear instance cache other than user table data, which is already accurate
4067 $this->clearInstanceCache();
4069 $this->saveOptions();
4070 return Status
::newGood();
4074 * If this user is logged-in and blocked,
4075 * block any IP address they've successfully logged in from.
4076 * @return bool A block was spread
4078 public function spreadAnyEditBlock() {
4079 if ( $this->isLoggedIn() && $this->isBlocked() ) {
4080 return $this->spreadBlock();
4087 * If this (non-anonymous) user is blocked,
4088 * block the IP address they've successfully logged in from.
4089 * @return bool A block was spread
4091 protected function spreadBlock() {
4092 wfDebug( __METHOD__
. "()\n" );
4094 if ( $this->mId
== 0 ) {
4098 $userblock = Block
::newFromTarget( $this->getName() );
4099 if ( !$userblock ) {
4103 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
4107 * Get whether the user is explicitly blocked from account creation.
4108 * @return bool|Block
4110 public function isBlockedFromCreateAccount() {
4111 $this->getBlockedStatus();
4112 if ( $this->mBlock
&& $this->mBlock
->prevents( 'createaccount' ) ) {
4113 return $this->mBlock
;
4116 # bug 13611: if the IP address the user is trying to create an account from is
4117 # blocked with createaccount disabled, prevent new account creation there even
4118 # when the user is logged in
4119 if ( $this->mBlockedFromCreateAccount
=== false && !$this->isAllowed( 'ipblock-exempt' ) ) {
4120 $this->mBlockedFromCreateAccount
= Block
::newFromTarget( null, $this->getRequest()->getIP() );
4122 return $this->mBlockedFromCreateAccount
instanceof Block
4123 && $this->mBlockedFromCreateAccount
->prevents( 'createaccount' )
4124 ?
$this->mBlockedFromCreateAccount
4129 * Get whether the user is blocked from using Special:Emailuser.
4132 public function isBlockedFromEmailuser() {
4133 $this->getBlockedStatus();
4134 return $this->mBlock
&& $this->mBlock
->prevents( 'sendemail' );
4138 * Get whether the user is allowed to create an account.
4141 public function isAllowedToCreateAccount() {
4142 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
4146 * Get this user's personal page title.
4148 * @return Title User's personal page title
4150 public function getUserPage() {
4151 return Title
::makeTitle( NS_USER
, $this->getName() );
4155 * Get this user's talk page title.
4157 * @return Title User's talk page title
4159 public function getTalkPage() {
4160 $title = $this->getUserPage();
4161 return $title->getTalkPage();
4165 * Determine whether the user is a newbie. Newbies are either
4166 * anonymous IPs, or the most recently created accounts.
4169 public function isNewbie() {
4170 return !$this->isAllowed( 'autoconfirmed' );
4174 * Check to see if the given clear-text password is one of the accepted passwords
4175 * @deprecated since 1.27, use AuthManager instead
4176 * @param string $password User password
4177 * @return bool True if the given password is correct, otherwise False
4179 public function checkPassword( $password ) {
4180 $manager = AuthManager
::singleton();
4181 $reqs = AuthenticationRequest
::loadRequestsFromSubmission(
4182 $manager->getAuthenticationRequests( AuthManager
::ACTION_LOGIN
),
4184 'username' => $this->getName(),
4185 'password' => $password,
4188 $res = AuthManager
::singleton()->beginAuthentication( $reqs, 'null:' );
4189 switch ( $res->status
) {
4190 case AuthenticationResponse
::PASS
:
4192 case AuthenticationResponse
::FAIL
:
4193 // Hope it's not a PreAuthenticationProvider that failed...
4194 \MediaWiki\Logger\LoggerFactory
::getInstance( 'authentication' )
4195 ->info( __METHOD__
. ': Authentication failed: ' . $res->message
->plain() );
4198 throw new BadMethodCallException(
4199 'AuthManager returned a response unsupported by ' . __METHOD__
4205 * Check if the given clear-text password matches the temporary password
4206 * sent by e-mail for password reset operations.
4208 * @deprecated since 1.27, use AuthManager instead
4209 * @param string $plaintext
4210 * @return bool True if matches, false otherwise
4212 public function checkTemporaryPassword( $plaintext ) {
4213 // Can't check the temporary password individually.
4214 return $this->checkPassword( $plaintext );
4218 * Initialize (if necessary) and return a session token value
4219 * which can be used in edit forms to show that the user's
4220 * login credentials aren't being hijacked with a foreign form
4224 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4225 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4226 * @return MediaWiki\Session\Token The new edit token
4228 public function getEditTokenObject( $salt = '', $request = null ) {
4229 if ( $this->isAnon() ) {
4230 return new LoggedOutEditToken();
4234 $request = $this->getRequest();
4236 return $request->getSession()->getToken( $salt );
4240 * Initialize (if necessary) and return a session token value
4241 * which can be used in edit forms to show that the user's
4242 * login credentials aren't being hijacked with a foreign form
4245 * The $salt for 'edit' and 'csrf' tokens is the default (empty string).
4248 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4249 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4250 * @return string The new edit token
4252 public function getEditToken( $salt = '', $request = null ) {
4253 return $this->getEditTokenObject( $salt, $request )->toString();
4257 * Get the embedded timestamp from a token.
4258 * @deprecated since 1.27, use \MediaWiki\Session\Token::getTimestamp instead.
4259 * @param string $val Input token
4262 public static function getEditTokenTimestamp( $val ) {
4263 wfDeprecated( __METHOD__
, '1.27' );
4264 return MediaWiki\Session\Token
::getTimestamp( $val );
4268 * Check given value against the token value stored in the session.
4269 * A match should confirm that the form was submitted from the
4270 * user's own login session, not a form submission from a third-party
4273 * @param string $val Input value to compare
4274 * @param string $salt Optional function-specific data for hashing
4275 * @param WebRequest|null $request Object to use or null to use $wgRequest
4276 * @param int $maxage Fail tokens older than this, in seconds
4277 * @return bool Whether the token matches
4279 public function matchEditToken( $val, $salt = '', $request = null, $maxage = null ) {
4280 return $this->getEditTokenObject( $salt, $request )->match( $val, $maxage );
4284 * Check given value against the token value stored in the session,
4285 * ignoring the suffix.
4287 * @param string $val Input value to compare
4288 * @param string $salt Optional function-specific data for hashing
4289 * @param WebRequest|null $request Object to use or null to use $wgRequest
4290 * @param int $maxage Fail tokens older than this, in seconds
4291 * @return bool Whether the token matches
4293 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null, $maxage = null ) {
4294 $val = substr( $val, 0, strspn( $val, '0123456789abcdef' ) ) . Token
::SUFFIX
;
4295 return $this->matchEditToken( $val, $salt, $request, $maxage );
4299 * Generate a new e-mail confirmation token and send a confirmation/invalidation
4300 * mail to the user's given address.
4302 * @param string $type Message to send, either "created", "changed" or "set"
4305 public function sendConfirmationMail( $type = 'created' ) {
4307 $expiration = null; // gets passed-by-ref and defined in next line.
4308 $token = $this->confirmationToken( $expiration );
4309 $url = $this->confirmationTokenUrl( $token );
4310 $invalidateURL = $this->invalidationTokenUrl( $token );
4311 $this->saveSettings();
4313 if ( $type == 'created' ||
$type === false ) {
4314 $message = 'confirmemail_body';
4315 } elseif ( $type === true ) {
4316 $message = 'confirmemail_body_changed';
4318 // Messages: confirmemail_body_changed, confirmemail_body_set
4319 $message = 'confirmemail_body_' . $type;
4322 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
4323 wfMessage( $message,
4324 $this->getRequest()->getIP(),
4327 $wgLang->userTimeAndDate( $expiration, $this ),
4329 $wgLang->userDate( $expiration, $this ),
4330 $wgLang->userTime( $expiration, $this ) )->text() );
4334 * Send an e-mail to this user's account. Does not check for
4335 * confirmed status or validity.
4337 * @param string $subject Message subject
4338 * @param string $body Message body
4339 * @param User|null $from Optional sending user; if unspecified, default
4340 * $wgPasswordSender will be used.
4341 * @param string $replyto Reply-To address
4344 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
4345 global $wgPasswordSender;
4347 if ( $from instanceof User
) {
4348 $sender = MailAddress
::newFromUser( $from );
4350 $sender = new MailAddress( $wgPasswordSender,
4351 wfMessage( 'emailsender' )->inContentLanguage()->text() );
4353 $to = MailAddress
::newFromUser( $this );
4355 return UserMailer
::send( $to, $sender, $subject, $body, [
4356 'replyTo' => $replyto,
4361 * Generate, store, and return a new e-mail confirmation code.
4362 * A hash (unsalted, since it's used as a key) is stored.
4364 * @note Call saveSettings() after calling this function to commit
4365 * this change to the database.
4367 * @param string &$expiration Accepts the expiration time
4368 * @return string New token
4370 protected function confirmationToken( &$expiration ) {
4371 global $wgUserEmailConfirmationTokenExpiry;
4373 $expires = $now +
$wgUserEmailConfirmationTokenExpiry;
4374 $expiration = wfTimestamp( TS_MW
, $expires );
4376 $token = MWCryptRand
::generateHex( 32 );
4377 $hash = md5( $token );
4378 $this->mEmailToken
= $hash;
4379 $this->mEmailTokenExpires
= $expiration;
4384 * Return a URL the user can use to confirm their email address.
4385 * @param string $token Accepts the email confirmation token
4386 * @return string New token URL
4388 protected function confirmationTokenUrl( $token ) {
4389 return $this->getTokenUrl( 'ConfirmEmail', $token );
4393 * Return a URL the user can use to invalidate their email address.
4394 * @param string $token Accepts the email confirmation token
4395 * @return string New token URL
4397 protected function invalidationTokenUrl( $token ) {
4398 return $this->getTokenUrl( 'InvalidateEmail', $token );
4402 * Internal function to format the e-mail validation/invalidation URLs.
4403 * This uses a quickie hack to use the
4404 * hardcoded English names of the Special: pages, for ASCII safety.
4406 * @note Since these URLs get dropped directly into emails, using the
4407 * short English names avoids insanely long URL-encoded links, which
4408 * also sometimes can get corrupted in some browsers/mailers
4409 * (bug 6957 with Gmail and Internet Explorer).
4411 * @param string $page Special page
4412 * @param string $token Token
4413 * @return string Formatted URL
4415 protected function getTokenUrl( $page, $token ) {
4416 // Hack to bypass localization of 'Special:'
4417 $title = Title
::makeTitle( NS_MAIN
, "Special:$page/$token" );
4418 return $title->getCanonicalURL();
4422 * Mark the e-mail address confirmed.
4424 * @note Call saveSettings() after calling this function to commit the change.
4428 public function confirmEmail() {
4429 // Check if it's already confirmed, so we don't touch the database
4430 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4431 if ( !$this->isEmailConfirmed() ) {
4432 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4433 Hooks
::run( 'ConfirmEmailComplete', [ $this ] );
4439 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4440 * address if it was already confirmed.
4442 * @note Call saveSettings() after calling this function to commit the change.
4443 * @return bool Returns true
4445 public function invalidateEmail() {
4447 $this->mEmailToken
= null;
4448 $this->mEmailTokenExpires
= null;
4449 $this->setEmailAuthenticationTimestamp( null );
4451 Hooks
::run( 'InvalidateEmailComplete', [ $this ] );
4456 * Set the e-mail authentication timestamp.
4457 * @param string $timestamp TS_MW timestamp
4459 public function setEmailAuthenticationTimestamp( $timestamp ) {
4461 $this->mEmailAuthenticated
= $timestamp;
4462 Hooks
::run( 'UserSetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated
] );
4466 * Is this user allowed to send e-mails within limits of current
4467 * site configuration?
4470 public function canSendEmail() {
4471 global $wgEnableEmail, $wgEnableUserEmail;
4472 if ( !$wgEnableEmail ||
!$wgEnableUserEmail ||
!$this->isAllowed( 'sendemail' ) ) {
4475 $canSend = $this->isEmailConfirmed();
4476 Hooks
::run( 'UserCanSendEmail', [ &$this, &$canSend ] );
4481 * Is this user allowed to receive e-mails within limits of current
4482 * site configuration?
4485 public function canReceiveEmail() {
4486 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4490 * Is this user's e-mail address valid-looking and confirmed within
4491 * limits of the current site configuration?
4493 * @note If $wgEmailAuthentication is on, this may require the user to have
4494 * confirmed their address by returning a code or using a password
4495 * sent to the address from the wiki.
4499 public function isEmailConfirmed() {
4500 global $wgEmailAuthentication;
4503 if ( Hooks
::run( 'EmailConfirmed', [ &$this, &$confirmed ] ) ) {
4504 if ( $this->isAnon() ) {
4507 if ( !Sanitizer
::validateEmail( $this->mEmail
) ) {
4510 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4520 * Check whether there is an outstanding request for e-mail confirmation.
4523 public function isEmailConfirmationPending() {
4524 global $wgEmailAuthentication;
4525 return $wgEmailAuthentication &&
4526 !$this->isEmailConfirmed() &&
4527 $this->mEmailToken
&&
4528 $this->mEmailTokenExpires
> wfTimestamp();
4532 * Get the timestamp of account creation.
4534 * @return string|bool|null Timestamp of account creation, false for
4535 * non-existent/anonymous user accounts, or null if existing account
4536 * but information is not in database.
4538 public function getRegistration() {
4539 if ( $this->isAnon() ) {
4543 return $this->mRegistration
;
4547 * Get the timestamp of the first edit
4549 * @return string|bool Timestamp of first edit, or false for
4550 * non-existent/anonymous user accounts.
4552 public function getFirstEditTimestamp() {
4553 if ( $this->getId() == 0 ) {
4554 return false; // anons
4556 $dbr = wfGetDB( DB_REPLICA
);
4557 $time = $dbr->selectField( 'revision', 'rev_timestamp',
4558 [ 'rev_user' => $this->getId() ],
4560 [ 'ORDER BY' => 'rev_timestamp ASC' ]
4563 return false; // no edits
4565 return wfTimestamp( TS_MW
, $time );
4569 * Get the permissions associated with a given list of groups
4571 * @param array $groups Array of Strings List of internal group names
4572 * @return array Array of Strings List of permission key names for given groups combined
4574 public static function getGroupPermissions( $groups ) {
4575 global $wgGroupPermissions, $wgRevokePermissions;
4577 // grant every granted permission first
4578 foreach ( $groups as $group ) {
4579 if ( isset( $wgGroupPermissions[$group] ) ) {
4580 $rights = array_merge( $rights,
4581 // array_filter removes empty items
4582 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4585 // now revoke the revoked permissions
4586 foreach ( $groups as $group ) {
4587 if ( isset( $wgRevokePermissions[$group] ) ) {
4588 $rights = array_diff( $rights,
4589 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4592 return array_unique( $rights );
4596 * Get all the groups who have a given permission
4598 * @param string $role Role to check
4599 * @return array Array of Strings List of internal group names with the given permission
4601 public static function getGroupsWithPermission( $role ) {
4602 global $wgGroupPermissions;
4603 $allowedGroups = [];
4604 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4605 if ( self
::groupHasPermission( $group, $role ) ) {
4606 $allowedGroups[] = $group;
4609 return $allowedGroups;
4613 * Check, if the given group has the given permission
4615 * If you're wanting to check whether all users have a permission, use
4616 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4620 * @param string $group Group to check
4621 * @param string $role Role to check
4624 public static function groupHasPermission( $group, $role ) {
4625 global $wgGroupPermissions, $wgRevokePermissions;
4626 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4627 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4631 * Check if all users may be assumed to have the given permission
4633 * We generally assume so if the right is granted to '*' and isn't revoked
4634 * on any group. It doesn't attempt to take grants or other extension
4635 * limitations on rights into account in the general case, though, as that
4636 * would require it to always return false and defeat the purpose.
4637 * Specifically, session-based rights restrictions (such as OAuth or bot
4638 * passwords) are applied based on the current session.
4641 * @param string $right Right to check
4644 public static function isEveryoneAllowed( $right ) {
4645 global $wgGroupPermissions, $wgRevokePermissions;
4648 // Use the cached results, except in unit tests which rely on
4649 // being able change the permission mid-request
4650 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4651 return $cache[$right];
4654 if ( !isset( $wgGroupPermissions['*'][$right] ) ||
!$wgGroupPermissions['*'][$right] ) {
4655 $cache[$right] = false;
4659 // If it's revoked anywhere, then everyone doesn't have it
4660 foreach ( $wgRevokePermissions as $rights ) {
4661 if ( isset( $rights[$right] ) && $rights[$right] ) {
4662 $cache[$right] = false;
4667 // Remove any rights that aren't allowed to the global-session user,
4668 // unless there are no sessions for this endpoint.
4669 if ( !defined( 'MW_NO_SESSION' ) ) {
4670 $allowedRights = SessionManager
::getGlobalSession()->getAllowedUserRights();
4671 if ( $allowedRights !== null && !in_array( $right, $allowedRights, true ) ) {
4672 $cache[$right] = false;
4677 // Allow extensions to say false
4678 if ( !Hooks
::run( 'UserIsEveryoneAllowed', [ $right ] ) ) {
4679 $cache[$right] = false;
4683 $cache[$right] = true;
4688 * Get the localized descriptive name for a group, if it exists
4690 * @param string $group Internal group name
4691 * @return string Localized descriptive group name
4693 public static function getGroupName( $group ) {
4694 $msg = wfMessage( "group-$group" );
4695 return $msg->isBlank() ?
$group : $msg->text();
4699 * Get the localized descriptive name for a member of a group, if it exists
4701 * @param string $group Internal group name
4702 * @param string $username Username for gender (since 1.19)
4703 * @return string Localized name for group member
4705 public static function getGroupMember( $group, $username = '#' ) {
4706 $msg = wfMessage( "group-$group-member", $username );
4707 return $msg->isBlank() ?
$group : $msg->text();
4711 * Return the set of defined explicit groups.
4712 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4713 * are not included, as they are defined automatically, not in the database.
4714 * @return array Array of internal group names
4716 public static function getAllGroups() {
4717 global $wgGroupPermissions, $wgRevokePermissions;
4719 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4720 self
::getImplicitGroups()
4725 * Get a list of all available permissions.
4726 * @return string[] Array of permission names
4728 public static function getAllRights() {
4729 if ( self
::$mAllRights === false ) {
4730 global $wgAvailableRights;
4731 if ( count( $wgAvailableRights ) ) {
4732 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
4734 self
::$mAllRights = self
::$mCoreRights;
4736 Hooks
::run( 'UserGetAllRights', [ &self
::$mAllRights ] );
4738 return self
::$mAllRights;
4742 * Get a list of implicit groups
4743 * @return array Array of Strings Array of internal group names
4745 public static function getImplicitGroups() {
4746 global $wgImplicitGroups;
4748 $groups = $wgImplicitGroups;
4749 # Deprecated, use $wgImplicitGroups instead
4750 Hooks
::run( 'UserGetImplicitGroups', [ &$groups ], '1.25' );
4756 * Get the title of a page describing a particular group
4758 * @param string $group Internal group name
4759 * @return Title|bool Title of the page if it exists, false otherwise
4761 public static function getGroupPage( $group ) {
4762 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
4763 if ( $msg->exists() ) {
4764 $title = Title
::newFromText( $msg->text() );
4765 if ( is_object( $title ) ) {
4773 * Create a link to the group in HTML, if available;
4774 * else return the group name.
4776 * @param string $group Internal name of the group
4777 * @param string $text The text of the link
4778 * @return string HTML link to the group
4780 public static function makeGroupLinkHTML( $group, $text = '' ) {
4781 if ( $text == '' ) {
4782 $text = self
::getGroupName( $group );
4784 $title = self
::getGroupPage( $group );
4786 return Linker
::link( $title, htmlspecialchars( $text ) );
4788 return htmlspecialchars( $text );
4793 * Create a link to the group in Wikitext, if available;
4794 * else return the group name.
4796 * @param string $group Internal name of the group
4797 * @param string $text The text of the link
4798 * @return string Wikilink to the group
4800 public static function makeGroupLinkWiki( $group, $text = '' ) {
4801 if ( $text == '' ) {
4802 $text = self
::getGroupName( $group );
4804 $title = self
::getGroupPage( $group );
4806 $page = $title->getFullText();
4807 return "[[$page|$text]]";
4814 * Returns an array of the groups that a particular group can add/remove.
4816 * @param string $group The group to check for whether it can add/remove
4817 * @return array Array( 'add' => array( addablegroups ),
4818 * 'remove' => array( removablegroups ),
4819 * 'add-self' => array( addablegroups to self),
4820 * 'remove-self' => array( removable groups from self) )
4822 public static function changeableByGroup( $group ) {
4823 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4832 if ( empty( $wgAddGroups[$group] ) ) {
4833 // Don't add anything to $groups
4834 } elseif ( $wgAddGroups[$group] === true ) {
4835 // You get everything
4836 $groups['add'] = self
::getAllGroups();
4837 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4838 $groups['add'] = $wgAddGroups[$group];
4841 // Same thing for remove
4842 if ( empty( $wgRemoveGroups[$group] ) ) {
4844 } elseif ( $wgRemoveGroups[$group] === true ) {
4845 $groups['remove'] = self
::getAllGroups();
4846 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4847 $groups['remove'] = $wgRemoveGroups[$group];
4850 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4851 if ( empty( $wgGroupsAddToSelf['user'] ) ||
$wgGroupsAddToSelf['user'] !== true ) {
4852 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4853 if ( is_int( $key ) ) {
4854 $wgGroupsAddToSelf['user'][] = $value;
4859 if ( empty( $wgGroupsRemoveFromSelf['user'] ) ||
$wgGroupsRemoveFromSelf['user'] !== true ) {
4860 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4861 if ( is_int( $key ) ) {
4862 $wgGroupsRemoveFromSelf['user'][] = $value;
4867 // Now figure out what groups the user can add to him/herself
4868 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
4870 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
4871 // No idea WHY this would be used, but it's there
4872 $groups['add-self'] = User
::getAllGroups();
4873 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
4874 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4877 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4879 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
4880 $groups['remove-self'] = User
::getAllGroups();
4881 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4882 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4889 * Returns an array of groups that this user can add and remove
4890 * @return array Array( 'add' => array( addablegroups ),
4891 * 'remove' => array( removablegroups ),
4892 * 'add-self' => array( addablegroups to self),
4893 * 'remove-self' => array( removable groups from self) )
4895 public function changeableGroups() {
4896 if ( $this->isAllowed( 'userrights' ) ) {
4897 // This group gives the right to modify everything (reverse-
4898 // compatibility with old "userrights lets you change
4900 // Using array_merge to make the groups reindexed
4901 $all = array_merge( User
::getAllGroups() );
4910 // Okay, it's not so simple, we will have to go through the arrays
4917 $addergroups = $this->getEffectiveGroups();
4919 foreach ( $addergroups as $addergroup ) {
4920 $groups = array_merge_recursive(
4921 $groups, $this->changeableByGroup( $addergroup )
4923 $groups['add'] = array_unique( $groups['add'] );
4924 $groups['remove'] = array_unique( $groups['remove'] );
4925 $groups['add-self'] = array_unique( $groups['add-self'] );
4926 $groups['remove-self'] = array_unique( $groups['remove-self'] );
4932 * Deferred version of incEditCountImmediate()
4934 public function incEditCount() {
4935 wfGetDB( DB_MASTER
)->onTransactionPreCommitOrIdle(
4937 $this->incEditCountImmediate();
4944 * Increment the user's edit-count field.
4945 * Will have no effect for anonymous users.
4948 public function incEditCountImmediate() {
4949 if ( $this->isAnon() ) {
4953 $dbw = wfGetDB( DB_MASTER
);
4954 // No rows will be "affected" if user_editcount is NULL
4957 [ 'user_editcount=user_editcount+1' ],
4958 [ 'user_id' => $this->getId(), 'user_editcount IS NOT NULL' ],
4961 // Lazy initialization check...
4962 if ( $dbw->affectedRows() == 0 ) {
4963 // Now here's a goddamn hack...
4964 $dbr = wfGetDB( DB_REPLICA
);
4965 if ( $dbr !== $dbw ) {
4966 // If we actually have a replica DB server, the count is
4967 // at least one behind because the current transaction
4968 // has not been committed and replicated.
4969 $this->mEditCount
= $this->initEditCount( 1 );
4971 // But if DB_REPLICA is selecting the master, then the
4972 // count we just read includes the revision that was
4973 // just added in the working transaction.
4974 $this->mEditCount
= $this->initEditCount();
4977 if ( $this->mEditCount
=== null ) {
4978 $this->getEditCount();
4979 $dbr = wfGetDB( DB_REPLICA
);
4980 $this->mEditCount +
= ( $dbr !== $dbw ) ?
1 : 0;
4982 $this->mEditCount++
;
4985 // Edit count in user cache too
4986 $this->invalidateCache();
4990 * Initialize user_editcount from data out of the revision table
4992 * @param int $add Edits to add to the count from the revision table
4993 * @return int Number of edits
4995 protected function initEditCount( $add = 0 ) {
4996 // Pull from a replica DB to be less cruel to servers
4997 // Accuracy isn't the point anyway here
4998 $dbr = wfGetDB( DB_REPLICA
);
4999 $count = (int)$dbr->selectField(
5002 [ 'rev_user' => $this->getId() ],
5005 $count = $count +
$add;
5007 $dbw = wfGetDB( DB_MASTER
);
5010 [ 'user_editcount' => $count ],
5011 [ 'user_id' => $this->getId() ],
5019 * Get the description of a given right
5021 * @param string $right Right to query
5022 * @return string Localized description of the right
5024 public static function getRightDescription( $right ) {
5025 $key = "right-$right";
5026 $msg = wfMessage( $key );
5027 return $msg->isBlank() ?
$right : $msg->text();
5031 * Make a new-style password hash
5033 * @param string $password Plain-text password
5034 * @param bool|string $salt Optional salt, may be random or the user ID.
5035 * If unspecified or false, will generate one automatically
5036 * @return string Password hash
5037 * @deprecated since 1.24, use Password class
5039 public static function crypt( $password, $salt = false ) {
5040 wfDeprecated( __METHOD__
, '1.24' );
5041 $passwordFactory = new PasswordFactory();
5042 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
5043 $hash = $passwordFactory->newFromPlaintext( $password );
5044 return $hash->toString();
5048 * Compare a password hash with a plain-text password. Requires the user
5049 * ID if there's a chance that the hash is an old-style hash.
5051 * @param string $hash Password hash
5052 * @param string $password Plain-text password to compare
5053 * @param string|bool $userId User ID for old-style password salt
5056 * @deprecated since 1.24, use Password class
5058 public static function comparePasswords( $hash, $password, $userId = false ) {
5059 wfDeprecated( __METHOD__
, '1.24' );
5061 // Check for *really* old password hashes that don't even have a type
5062 // The old hash format was just an md5 hex hash, with no type information
5063 if ( preg_match( '/^[0-9a-f]{32}$/', $hash ) ) {
5064 global $wgPasswordSalt;
5065 if ( $wgPasswordSalt ) {
5066 $password = ":B:{$userId}:{$hash}";
5068 $password = ":A:{$hash}";
5072 $passwordFactory = new PasswordFactory();
5073 $passwordFactory->init( RequestContext
::getMain()->getConfig() );
5074 $hash = $passwordFactory->newFromCiphertext( $hash );
5075 return $hash->equals( $password );
5079 * Add a newuser log entry for this user.
5080 * Before 1.19 the return value was always true.
5082 * @deprecated since 1.27, AuthManager handles logging
5083 * @param string|bool $action Account creation type.
5084 * - String, one of the following values:
5085 * - 'create' for an anonymous user creating an account for himself.
5086 * This will force the action's performer to be the created user itself,
5087 * no matter the value of $wgUser
5088 * - 'create2' for a logged in user creating an account for someone else
5089 * - 'byemail' when the created user will receive its password by e-mail
5090 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
5091 * - Boolean means whether the account was created by e-mail (deprecated):
5092 * - true will be converted to 'byemail'
5093 * - false will be converted to 'create' if this object is the same as
5094 * $wgUser and to 'create2' otherwise
5095 * @param string $reason User supplied reason
5098 public function addNewUserLogEntry( $action = false, $reason = '' ) {
5099 return true; // disabled
5103 * Add an autocreate newuser log entry for this user
5104 * Used by things like CentralAuth and perhaps other authplugins.
5105 * Consider calling addNewUserLogEntry() directly instead.
5107 * @deprecated since 1.27, AuthManager handles logging
5110 public function addNewUserLogEntryAutoCreate() {
5111 $this->addNewUserLogEntry( 'autocreate' );
5117 * Load the user options either from cache, the database or an array
5119 * @param array $data Rows for the current user out of the user_properties table
5121 protected function loadOptions( $data = null ) {
5126 if ( $this->mOptionsLoaded
) {
5130 $this->mOptions
= self
::getDefaultOptions();
5132 if ( !$this->getId() ) {
5133 // For unlogged-in users, load language/variant options from request.
5134 // There's no need to do it for logged-in users: they can set preferences,
5135 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
5136 // so don't override user's choice (especially when the user chooses site default).
5137 $variant = $wgContLang->getDefaultVariant();
5138 $this->mOptions
['variant'] = $variant;
5139 $this->mOptions
['language'] = $variant;
5140 $this->mOptionsLoaded
= true;
5144 // Maybe load from the object
5145 if ( !is_null( $this->mOptionOverrides
) ) {
5146 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
5147 foreach ( $this->mOptionOverrides
as $key => $value ) {
5148 $this->mOptions
[$key] = $value;
5151 if ( !is_array( $data ) ) {
5152 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
5153 // Load from database
5154 $dbr = ( $this->queryFlagsUsed
& self
::READ_LATEST
)
5155 ?
wfGetDB( DB_MASTER
)
5156 : wfGetDB( DB_REPLICA
);
5158 $res = $dbr->select(
5160 [ 'up_property', 'up_value' ],
5161 [ 'up_user' => $this->getId() ],
5165 $this->mOptionOverrides
= [];
5167 foreach ( $res as $row ) {
5168 $data[$row->up_property
] = $row->up_value
;
5171 foreach ( $data as $property => $value ) {
5172 $this->mOptionOverrides
[$property] = $value;
5173 $this->mOptions
[$property] = $value;
5177 $this->mOptionsLoaded
= true;
5179 Hooks
::run( 'UserLoadOptions', [ $this, &$this->mOptions
] );
5183 * Saves the non-default options for this user, as previously set e.g. via
5184 * setOption(), in the database's "user_properties" (preferences) table.
5185 * Usually used via saveSettings().
5187 protected function saveOptions() {
5188 $this->loadOptions();
5190 // Not using getOptions(), to keep hidden preferences in database
5191 $saveOptions = $this->mOptions
;
5193 // Allow hooks to abort, for instance to save to a global profile.
5194 // Reset options to default state before saving.
5195 if ( !Hooks
::run( 'UserSaveOptions', [ $this, &$saveOptions ] ) ) {
5199 $userId = $this->getId();
5201 $insert_rows = []; // all the new preference rows
5202 foreach ( $saveOptions as $key => $value ) {
5203 // Don't bother storing default values
5204 $defaultOption = self
::getDefaultOption( $key );
5205 if ( ( $defaultOption === null && $value !== false && $value !== null )
5206 ||
$value != $defaultOption
5209 'up_user' => $userId,
5210 'up_property' => $key,
5211 'up_value' => $value,
5216 $dbw = wfGetDB( DB_MASTER
);
5218 $res = $dbw->select( 'user_properties',
5219 [ 'up_property', 'up_value' ], [ 'up_user' => $userId ], __METHOD__
);
5221 // Find prior rows that need to be removed or updated. These rows will
5222 // all be deleted (the latter so that INSERT IGNORE applies the new values).
5224 foreach ( $res as $row ) {
5225 if ( !isset( $saveOptions[$row->up_property
] )
5226 ||
strcmp( $saveOptions[$row->up_property
], $row->up_value
) != 0
5228 $keysDelete[] = $row->up_property
;
5232 if ( count( $keysDelete ) ) {
5233 // Do the DELETE by PRIMARY KEY for prior rows.
5234 // In the past a very large portion of calls to this function are for setting
5235 // 'rememberpassword' for new accounts (a preference that has since been removed).
5236 // Doing a blanket per-user DELETE for new accounts with no rows in the table
5237 // caused gap locks on [max user ID,+infinity) which caused high contention since
5238 // updates would pile up on each other as they are for higher (newer) user IDs.
5239 // It might not be necessary these days, but it shouldn't hurt either.
5240 $dbw->delete( 'user_properties',
5241 [ 'up_user' => $userId, 'up_property' => $keysDelete ], __METHOD__
);
5243 // Insert the new preference rows
5244 $dbw->insert( 'user_properties', $insert_rows, __METHOD__
, [ 'IGNORE' ] );
5248 * Lazily instantiate and return a factory object for making passwords
5250 * @deprecated since 1.27, create a PasswordFactory directly instead
5251 * @return PasswordFactory
5253 public static function getPasswordFactory() {
5254 wfDeprecated( __METHOD__
, '1.27' );
5255 $ret = new PasswordFactory();
5256 $ret->init( RequestContext
::getMain()->getConfig() );
5261 * Provide an array of HTML5 attributes to put on an input element
5262 * intended for the user to enter a new password. This may include
5263 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
5265 * Do *not* use this when asking the user to enter his current password!
5266 * Regardless of configuration, users may have invalid passwords for whatever
5267 * reason (e.g., they were set before requirements were tightened up).
5268 * Only use it when asking for a new password, like on account creation or
5271 * Obviously, you still need to do server-side checking.
5273 * NOTE: A combination of bugs in various browsers means that this function
5274 * actually just returns array() unconditionally at the moment. May as
5275 * well keep it around for when the browser bugs get fixed, though.
5277 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
5279 * @deprecated since 1.27
5280 * @return array Array of HTML attributes suitable for feeding to
5281 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
5282 * That will get confused by the boolean attribute syntax used.)
5284 public static function passwordChangeInputAttribs() {
5285 global $wgMinimalPasswordLength;
5287 if ( $wgMinimalPasswordLength == 0 ) {
5291 # Note that the pattern requirement will always be satisfied if the
5292 # input is empty, so we need required in all cases.
5294 # @todo FIXME: Bug 23769: This needs to not claim the password is required
5295 # if e-mail confirmation is being used. Since HTML5 input validation
5296 # is b0rked anyway in some browsers, just return nothing. When it's
5297 # re-enabled, fix this code to not output required for e-mail
5299 # $ret = array( 'required' );
5302 # We can't actually do this right now, because Opera 9.6 will print out
5303 # the entered password visibly in its error message! When other
5304 # browsers add support for this attribute, or Opera fixes its support,
5305 # we can add support with a version check to avoid doing this on Opera
5306 # versions where it will be a problem. Reported to Opera as
5307 # DSK-262266, but they don't have a public bug tracker for us to follow.
5309 if ( $wgMinimalPasswordLength > 1 ) {
5310 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
5311 $ret['title'] = wfMessage( 'passwordtooshort' )
5312 ->numParams( $wgMinimalPasswordLength )->text();
5320 * Return the list of user fields that should be selected to create
5321 * a new user object.
5324 public static function selectFields() {
5332 'user_email_authenticated',
5334 'user_email_token_expires',
5335 'user_registration',
5341 * Factory function for fatal permission-denied errors
5344 * @param string $permission User right required
5347 static function newFatalPermissionDeniedStatus( $permission ) {
5350 $groups = array_map(
5351 [ 'User', 'makeGroupLinkWiki' ],
5352 User
::getGroupsWithPermission( $permission )
5356 return Status
::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
5358 return Status
::newFatal( 'badaccess-group0' );
5363 * Get a new instance of this user that was loaded from the master via a locking read
5365 * Use this instead of the main context User when updating that user. This avoids races
5366 * where that user was loaded from a replica DB or even the master but without proper locks.
5368 * @return User|null Returns null if the user was not found in the DB
5371 public function getInstanceForUpdate() {
5372 if ( !$this->getId() ) {
5373 return null; // anon
5376 $user = self
::newFromId( $this->getId() );
5377 if ( !$user->loadFromId( self
::READ_EXCLUSIVE
) ) {
5385 * Checks if two user objects point to the same user.
5391 public function equals( User
$user ) {
5392 return $this->getName() === $user->getName();